Modified code to support both Python 2.7 and 3.x
[snaps.git] / snaps / openstack / create_router.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 import logging
16
17 from neutronclient.common.exceptions import NotFound
18
19 from snaps.openstack.create_network import PortSettings
20 from snaps.openstack.utils import neutron_utils, keystone_utils
21
22 __author__ = 'spisarski'
23
24 logger = logging.getLogger('OpenStackNetwork')
25
26
27 class OpenStackRouter:
28     """
29     Class responsible for creating a router in OpenStack
30     """
31
32     def __init__(self, os_creds, router_settings):
33         """
34         Constructor - all parameters are required
35         :param os_creds: The credentials to connect with OpenStack
36         :param router_settings: The settings used to create a router object (must be an instance of the
37                                 RouterSettings class)
38         """
39         self.__os_creds = os_creds
40
41         if not router_settings:
42             raise Exception('router_settings is required')
43
44         self.router_settings = router_settings
45         self.__neutron = neutron_utils.neutron_client(os_creds)
46
47         # Attributes instantiated on create()
48         self.__router = None
49         self.__internal_subnets = list()
50         self.__internal_router_interface = None
51
52         # Dict where the port object is the key and any newly created router interfaces are the value
53         self.__ports = list()
54
55     def create(self, cleanup=False):
56         """
57         Responsible for creating the router.
58         :param cleanup: When true, only perform lookups for OpenStack objects.
59         :return: the router object
60         """
61         logger.debug('Creating Router with name - ' + self.router_settings.name)
62         existing = False
63         router_inst = neutron_utils.get_router_by_name(self.__neutron, self.router_settings.name)
64         if router_inst:
65             self.__router = router_inst
66             existing = True
67         else:
68             if not cleanup:
69                 self.__router = neutron_utils.create_router(self.__neutron, self.__os_creds, self.router_settings)
70
71         for internal_subnet_name in self.router_settings.internal_subnets:
72             internal_subnet = neutron_utils.get_subnet_by_name(self.__neutron, internal_subnet_name)
73             if internal_subnet:
74                 self.__internal_subnets.append(internal_subnet)
75                 if internal_subnet and not cleanup and not existing:
76                     logger.debug('Adding router to subnet...')
77                     self.__internal_router_interface = neutron_utils.add_interface_router(
78                         self.__neutron, self.__router, subnet=internal_subnet)
79             else:
80                 raise Exception('Subnet not found with name ' + internal_subnet_name)
81
82         for port_setting in self.router_settings.port_settings:
83             port = neutron_utils.get_port_by_name(self.__neutron, port_setting.name)
84             logger.info('Retrieved port ' + port_setting.name + ' for router - ' + self.router_settings.name)
85             if port:
86                 self.__ports.append(port)
87
88             if not port and not cleanup and not existing:
89                 port = neutron_utils.create_port(self.__neutron, self.__os_creds, port_setting)
90                 if port:
91                     logger.info('Created port ' + port_setting.name + ' for router - ' + self.router_settings.name)
92                     self.__ports.append(port)
93                     neutron_utils.add_interface_router(self.__neutron, self.__router, port=port)
94                 else:
95                     raise Exception('Error creating port with name - ' + port_setting.name)
96
97         return self.__router
98
99     def clean(self):
100         """
101         Removes and deletes all items created in reverse order.
102         """
103         for port in self.__ports:
104             logger.info('Removing router interface from router ' + self.router_settings.name +
105                         ' and port ' + port['port']['name'])
106             try:
107                 neutron_utils.remove_interface_router(self.__neutron, self.__router, port=port)
108             except NotFound:
109                 pass
110         self.__ports = list()
111
112         for internal_subnet in self.__internal_subnets:
113             logger.info('Removing router interface from router ' + self.router_settings.name +
114                         ' and subnet ' + internal_subnet['subnet']['name'])
115             try:
116                 neutron_utils.remove_interface_router(self.__neutron, self.__router, subnet=internal_subnet)
117             except NotFound:
118                 pass
119         self.__internal_subnets = list()
120
121         if self.__router:
122             logger.info('Removing router ' + self.router_settings.name)
123             try:
124                 neutron_utils.delete_router(self.__neutron, self.__router)
125             except NotFound:
126                 pass
127             self.__router = None
128
129     def get_router(self):
130         """
131         Returns the OpenStack router object
132         :return:
133         """
134         return self.__router
135
136     def get_internal_router_interface(self):
137         """
138         Returns the OpenStack internal router interface object
139         :return:
140         """
141         return self.__internal_router_interface
142
143
144 class RouterSettings:
145     """
146     Class representing a router configuration
147     """
148
149     def __init__(self, config=None, name=None, project_name=None, external_gateway=None,
150                  admin_state_up=True, external_fixed_ips=None, internal_subnets=list(),
151                  port_settings=list()):
152         """
153         Constructor - all parameters are optional
154         :param config: Should be a dict object containing the configuration settings using the attribute names below
155                        as each member's the key and overrides any of the other parameters.
156         :param name: The router name.
157         :param project_name: The name of the project who owns the network. Only administrative users can specify a
158                              project ID other than their own. You cannot change this value through authorization
159                              policies.
160         :param external_gateway: Name of the external network to which to route
161         :param admin_state_up: The administrative status of the router. True = up / False = down (default True)
162         :param external_fixed_ips: Dictionary containing the IP address parameters.
163         :param internal_subnets: List of subnet names to which to connect this router for Floating IP purposes
164         :param port_settings: List of PortSettings objects
165         :return:
166         """
167         if config:
168             self.name = config.get('name')
169             self.project_name = config.get('project_name')
170             self.external_gateway = config.get('external_gateway')
171
172             self.admin_state_up = config.get('admin_state_up')
173             self.enable_snat = config.get('enable_snat')
174             self.external_fixed_ips = config.get('external_fixed_ips')
175             if config.get('internal_subnets'):
176                 self.internal_subnets = config['internal_subnets']
177             else:
178                 self.internal_subnets = internal_subnets
179
180             self.port_settings = list()
181             if config.get('interfaces'):
182                 interfaces = config['interfaces']
183                 for interface in interfaces:
184                     if interface.get('port'):
185                         self.port_settings.append(PortSettings(config=interface['port']))
186         else:
187             self.name = name
188             self.project_name = project_name
189             self.external_gateway = external_gateway
190             self.admin_state_up = admin_state_up
191             self.external_fixed_ips = external_fixed_ips
192             self.internal_subnets = internal_subnets
193             self.port_settings = port_settings
194
195         if not self.name:
196             raise Exception('Name is required')
197
198     def dict_for_neutron(self, neutron, os_creds):
199         """
200         Returns a dictionary object representing this object.
201         This is meant to be converted into JSON designed for use by the Neutron API
202
203         TODO - expand automated testing to exercise all parameters
204         :param neutron: The neutron client to retrieve external network information if necessary
205         :param os_creds: The OpenStack credentials
206         :return: the dictionary object
207         """
208         out = dict()
209         ext_gw = dict()
210
211         project_id = None
212
213         if self.name:
214             out['name'] = self.name
215         if self.project_name:
216             keystone = keystone_utils.keystone_client(os_creds)
217             project = keystone_utils.get_project(keystone, self.project_name)
218             project_id = None
219             if project:
220                 project_id = project.id
221             if project_id:
222                 out['project_id'] = project_id
223             else:
224                 raise Exception('Could not find project ID for project named - ' + self.project_name)
225         if self.admin_state_up is not None:
226             out['admin_state_up'] = self.admin_state_up
227         if self.external_gateway:
228             ext_net = neutron_utils.get_network(neutron, self.external_gateway, project_id)
229             if ext_net:
230                 ext_gw['network_id'] = ext_net['network']['id']
231                 out['external_gateway_info'] = ext_gw
232             else:
233                 raise Exception('Could not find the external network named - ' + self.external_gateway)
234
235         # TODO: Enable SNAT option for Router
236         # TODO: Add external_fixed_ips Tests
237
238         return {'router': out}