1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
19 from heatclient.exc import HTTPNotFound
21 from snaps.openstack.utils import heat_utils
23 __author__ = 'spisarski'
25 logger = logging.getLogger('create_stack')
27 STACK_COMPLETE_TIMEOUT = 1200
29 STATUS_CREATE_COMPLETE = 'CREATE_COMPLETE'
30 STATUS_DELETE_COMPLETE = 'DELETE_COMPLETE'
33 class OpenStackHeatStack:
35 Class responsible for creating an heat stack in OpenStack
38 def __init__(self, os_creds, stack_settings):
41 :param os_creds: The OpenStack connection credentials
42 :param stack_settings: The stack settings
45 self.__os_creds = os_creds
46 self.stack_settings = stack_settings
48 self.__heat_cli = None
50 def create(self, cleanup=False):
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
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)
59 logger.info('Found stack with name - ' + self.stack_settings.name)
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)
68 raise StackCreationError('Stack was not created or activated in the alloted amount of time')
70 logger.info('Did not create stack due to cleanup mode')
76 Cleanse environment of all artifacts
81 heat_utils.delete_stack(self.__heat_cli, self.__stack)
89 Returns the domain Stack object as it was populated when create() was called
94 def get_outputs(self):
96 Returns the list of outputs as contained on the OpenStack Heat Stack object
99 return heat_utils.get_stack_outputs(self.__heat_cli, self.__stack.id)
101 def get_status(self):
103 Returns the list of outputs as contained on the OpenStack Heat Stack object
106 return heat_utils.get_stack_status(self.__heat_cli, self.__stack.id)
108 def stack_complete(self, block=False, timeout=None, poll_interval=POLL_INTERVAL):
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
117 timeout = self.stack_settings.stack_create_timeout
118 return self._stack_status_check(STATUS_CREATE_COMPLETE, block, timeout, poll_interval)
120 def _stack_status_check(self, expected_status_code, block, timeout, poll_interval):
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
129 # sleep and wait for stack status change
133 start = time.time() - timeout
135 while timeout > time.time() - start:
136 status = self._status(expected_status_code)
138 logger.debug('Stack is active with name - ' + self.stack_settings.name)
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)))
145 logger.error('Timeout checking for stack status for ' + expected_status_code)
148 def _status(self, expected_status_code):
150 Returns True when active else False
151 :param expected_status_code: stack status evaluated with this string value
154 status = self.get_status()
156 logger.warning('Cannot stack status for stack with ID - ' + self.__stack.id)
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
166 def __init__(self, config=None, name=None, template=None, template_path=None, env_values=None,
167 stack_create_timeout=STACK_COMPLETE_TIMEOUT):
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)
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']
186 self.stack_create_timeout = stack_create_timeout
189 self.template = template
190 self.template_path = template_path
191 self.env_values = env_values
192 self.stack_create_timeout = stack_create_timeout
195 raise StackSettingsError('name is required')
197 if not self.template and not self.template_path:
198 raise StackSettingsError('A Heat template is required')
201 class StackSettingsError(Exception):
203 Exception to be thrown when an stack settings are incorrect
205 def __init__(self, message):
206 Exception.__init__(self, message)
209 class StackCreationError(Exception):
211 Exception to be thrown when an stack cannot be created
213 def __init__(self, message):
214 Exception.__init__(self, message)