Refactoring of NetworkSettings to extend NetworkConfig
[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.config.router import RouterConfig
20 from snaps.openstack.openstack_creator import OpenStackNetworkObject
21 from snaps.openstack.utils import neutron_utils
22
23 __author__ = 'spisarski'
24
25 logger = logging.getLogger('OpenStackNetwork')
26
27
28 class OpenStackRouter(OpenStackNetworkObject):
29     """
30     Class responsible for managing a router in OpenStack
31     """
32
33     def __init__(self, os_creds, router_settings):
34         """
35         Constructor - all parameters are required
36         :param os_creds: The credentials to connect with OpenStack
37         :param router_settings: The settings used to create a router object
38                                 (must be an instance of the RouterConfig
39                                 class)
40         """
41         super(self.__class__, self).__init__(os_creds)
42
43         if not router_settings:
44             raise RouterCreationError('router_settings is required')
45
46         self.router_settings = router_settings
47
48         # Attributes instantiated on create()
49         self.__router = None
50         self.__internal_subnets = list()
51         self.__internal_router_interface = None
52
53         # Dict where the port object is the key and any newly created router
54         # interfaces are the value
55         self.__ports = list()
56
57     def initialize(self):
58         """
59         Loads the existing router.
60         :return: the Router domain object
61         """
62         super(self.__class__, self).initialize()
63
64         self.__router = neutron_utils.get_router(
65             self._neutron, router_settings=self.router_settings)
66
67         for internal_subnet_name in self.router_settings.internal_subnets:
68             internal_subnet = neutron_utils.get_subnet(
69                 self._neutron, subnet_name=internal_subnet_name)
70             if internal_subnet:
71                 self.__internal_subnets.append(internal_subnet)
72             else:
73                 raise RouterCreationError(
74                     'Subnet not found with name ' + internal_subnet_name)
75
76         for port_setting in self.router_settings.port_settings:
77             port = neutron_utils.get_port(
78                 self._neutron, port_settings=port_setting)
79             if port:
80                 self.__ports.append(port)
81
82         return self.__router
83
84     def create(self):
85         """
86         Responsible for creating the router.
87         :return: the Router domain object
88         """
89         self.initialize()
90
91         if not self.__router:
92             self.__router = neutron_utils.create_router(
93                 self._neutron, self._os_creds, self.router_settings)
94
95             for internal_subnet_name in self.router_settings.internal_subnets:
96                 internal_subnet = neutron_utils.get_subnet(
97                     self._neutron, subnet_name=internal_subnet_name)
98                 if internal_subnet:
99                     self.__internal_subnets.append(internal_subnet)
100                     if internal_subnet:
101                         logger.debug('Adding router to subnet...')
102                         router_intf = neutron_utils.add_interface_router(
103                             self._neutron, self.__router,
104                             subnet=internal_subnet)
105                         self.__internal_router_interface = router_intf
106                 else:
107                     raise RouterCreationError(
108                         'Subnet not found with name ' + internal_subnet_name)
109
110             for port_setting in self.router_settings.port_settings:
111                 port = neutron_utils.get_port(
112                     self._neutron, port_settings=port_setting)
113                 logger.info(
114                     'Retrieved port %s for router - %s', port_setting.name,
115                     self.router_settings.name)
116                 if port:
117                     self.__ports.append(port)
118
119                 if not port:
120                     port = neutron_utils.create_port(
121                         self._neutron, self._os_creds, port_setting)
122                     if port:
123                         logger.info(
124                             'Created port %s for router - %s',
125                             port_setting.name,
126                             self.router_settings.name)
127                         self.__ports.append(port)
128                         neutron_utils.add_interface_router(self._neutron,
129                                                            self.__router,
130                                                            port=port)
131                     else:
132                         raise RouterCreationError(
133                             'Error creating port with name - '
134                             + port_setting.name)
135
136         self.__router = neutron_utils.get_router_by_id(
137             self._neutron, self.__router.id)
138         return self.__router
139
140     def clean(self):
141         """
142         Removes and deletes all items created in reverse order.
143         """
144         for port in self.__ports:
145             logger.info(
146                 'Removing router interface from router %s and port %s',
147                 self.router_settings.name, port.name)
148             try:
149                 neutron_utils.remove_interface_router(self._neutron,
150                                                       self.__router, port=port)
151             except NotFound:
152                 pass
153         self.__ports = list()
154
155         for internal_subnet in self.__internal_subnets:
156             logger.info(
157                 'Removing router interface from router %s and subnet %s',
158                 self.router_settings.name, internal_subnet.name)
159             try:
160                 neutron_utils.remove_interface_router(self._neutron,
161                                                       self.__router,
162                                                       subnet=internal_subnet)
163             except NotFound:
164                 pass
165         self.__internal_subnets = list()
166
167         if self.__router:
168             logger.info('Removing router ' + self.router_settings.name)
169             try:
170                 neutron_utils.delete_router(self._neutron, self.__router)
171             except NotFound:
172                 pass
173             self.__router = None
174
175     def get_router(self):
176         """
177         Returns the OpenStack router object
178         :return:
179         """
180         return self.__router
181
182     def get_internal_router_interface(self):
183         """
184         Returns the OpenStack internal router interface object
185         :return:
186         """
187         return self.__internal_router_interface
188
189
190 class RouterCreationError(Exception):
191     """
192     Exception to be thrown when an router instance cannot be created
193     """
194
195
196 class RouterSettings(RouterConfig):
197     """
198     Class to hold the configuration settings required for creating OpenStack
199     router objects
200     deprecated
201     """
202
203     def __init__(self, **kwargs):
204         from warnings import warn
205         warn('Use snaps.config.router.RouterConfig instead',
206              DeprecationWarning)
207         super(self.__class__, self).__init__(**kwargs)