Changes UserSettings constructor to use kwargs.
[snaps.git] / snaps / openstack / create_stack.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
16 import logging
17 import time
18
19 from heatclient.exc import HTTPNotFound
20
21 from snaps.openstack.utils import heat_utils
22
23 __author__ = 'spisarski'
24
25 logger = logging.getLogger('create_stack')
26
27 STACK_COMPLETE_TIMEOUT = 1200
28 POLL_INTERVAL = 3
29 STATUS_CREATE_COMPLETE = 'CREATE_COMPLETE'
30 STATUS_DELETE_COMPLETE = 'DELETE_COMPLETE'
31
32
33 class OpenStackHeatStack:
34     """
35     Class responsible for creating an heat stack in OpenStack
36     """
37
38     def __init__(self, os_creds, stack_settings):
39         """
40         Constructor
41         :param os_creds: The OpenStack connection credentials
42         :param stack_settings: The stack settings
43         :return:
44         """
45         self.__os_creds = os_creds
46         self.stack_settings = stack_settings
47         self.__stack = None
48         self.__heat_cli = None
49
50     def create(self, cleanup=False):
51         """
52         Creates the heat stack in OpenStack if it does not already exist and returns the domain Stack object
53         :param cleanup: Denotes whether or not this is being called for cleanup or not
54         :return: The OpenStack Stack object
55         """
56         self.__heat_cli = heat_utils.heat_client(self.__os_creds)
57         self.__stack = heat_utils.get_stack_by_name(self.__heat_cli, self.stack_settings.name)
58         if self.__stack:
59             logger.info('Found stack with name - ' + self.stack_settings.name)
60             return self.__stack
61         elif not cleanup:
62             self.__stack = heat_utils.create_stack(self.__heat_cli, self.stack_settings)
63             logger.info('Created stack with name - ' + self.stack_settings.name)
64             if self.__stack and self.stack_complete(block=True):
65                 logger.info('Stack is now active with name - ' + self.stack_settings.name)
66                 return self.__stack
67             else:
68                 raise StackCreationError('Stack was not created or activated in the alloted amount of time')
69         else:
70             logger.info('Did not create stack due to cleanup mode')
71
72         return self.__stack
73
74     def clean(self):
75         """
76         Cleanse environment of all artifacts
77         :return: void
78         """
79         if self.__stack:
80             try:
81                 heat_utils.delete_stack(self.__heat_cli, self.__stack)
82             except HTTPNotFound:
83                 pass
84
85         self.__stack = None
86
87     def get_stack(self):
88         """
89         Returns the domain Stack object as it was populated when create() was called
90         :return: the object
91         """
92         return self.__stack
93
94     def get_outputs(self):
95         """
96         Returns the list of outputs as contained on the OpenStack Heat Stack object
97         :return:
98         """
99         return heat_utils.get_stack_outputs(self.__heat_cli, self.__stack.id)
100
101     def get_status(self):
102         """
103         Returns the list of outputs as contained on the OpenStack Heat Stack object
104         :return:
105         """
106         return heat_utils.get_stack_status(self.__heat_cli, self.__stack.id)
107
108     def stack_complete(self, block=False, timeout=None, poll_interval=POLL_INTERVAL):
109         """
110         Returns true when the stack status returns the value of expected_status_code
111         :param block: When true, thread will block until active or timeout value in seconds has been exceeded (False)
112         :param timeout: The timeout value
113         :param poll_interval: The polling interval in seconds
114         :return: T/F
115         """
116         if not timeout:
117             timeout = self.stack_settings.stack_create_timeout
118         return self._stack_status_check(STATUS_CREATE_COMPLETE, block, timeout, poll_interval)
119
120     def _stack_status_check(self, expected_status_code, block, timeout, poll_interval):
121         """
122         Returns true when the stack status returns the value of expected_status_code
123         :param expected_status_code: stack status evaluated with this string value
124         :param block: When true, thread will block until active or timeout value in seconds has been exceeded (False)
125         :param timeout: The timeout value
126         :param poll_interval: The polling interval in seconds
127         :return: T/F
128         """
129         # sleep and wait for stack status change
130         if block:
131             start = time.time()
132         else:
133             start = time.time() - timeout
134
135         while timeout > time.time() - start:
136             status = self._status(expected_status_code)
137             if status:
138                 logger.debug('Stack is active with name - ' + self.stack_settings.name)
139                 return True
140
141             logger.debug('Retry querying stack status in ' + str(poll_interval) + ' seconds')
142             time.sleep(poll_interval)
143             logger.debug('Stack status query timeout in ' + str(timeout - (time.time() - start)))
144
145         logger.error('Timeout checking for stack status for ' + expected_status_code)
146         return False
147
148     def _status(self, expected_status_code):
149         """
150         Returns True when active else False
151         :param expected_status_code: stack status evaluated with this string value
152         :return: T/F
153         """
154         status = self.get_status()
155         if not status:
156             logger.warning('Cannot stack status for stack with ID - ' + self.__stack.id)
157             return False
158
159         if status == 'ERROR':
160             raise StackCreationError('Stack had an error during deployment')
161         logger.debug('Stack status is - ' + status)
162         return status == expected_status_code
163
164
165 class StackSettings:
166     def __init__(self, config=None, name=None, template=None, template_path=None, env_values=None,
167                  stack_create_timeout=STACK_COMPLETE_TIMEOUT):
168         """
169         Constructor
170         :param config: dict() object containing the configuration settings using the attribute names below as each
171                        member's the key and overrides any of the other parameters.
172         :param name: the stack's name (required)
173         :param template: the heat template in dict() format (required if template_path attribute is None)
174         :param template_path: the location of the heat template file (required if template attribute is None)
175         :param env_values: k/v pairs of strings for substitution of template default values (optional)
176         """
177
178         if config:
179             self.name = config.get('name')
180             self.template = config.get('template')
181             self.template_path = config.get('template_path')
182             self.env_values = config.get('env_values')
183             if 'stack_create_timeout' in config:
184                 self.stack_create_timeout = config['stack_create_timeout']
185             else:
186                 self.stack_create_timeout = stack_create_timeout
187         else:
188             self.name = name
189             self.template = template
190             self.template_path = template_path
191             self.env_values = env_values
192             self.stack_create_timeout = stack_create_timeout
193
194         if not self.name:
195             raise StackSettingsError('name is required')
196
197         if not self.template and not self.template_path:
198             raise StackSettingsError('A Heat template is required')
199
200
201 class StackSettingsError(Exception):
202     """
203     Exception to be thrown when an stack settings are incorrect
204     """
205     def __init__(self, message):
206         Exception.__init__(self, message)
207
208
209 class StackCreationError(Exception):
210     """
211     Exception to be thrown when an stack cannot be created
212     """
213     def __init__(self, message):
214         Exception.__init__(self, message)