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.client import Client
20 from heatclient.common.template_format import yaml_loader
21 from novaclient.exceptions import NotFound
22 from oslo_serialization import jsonutils
24 from snaps import file_utils
25 from snaps.domain.stack import Stack, Resource, Output
27 from snaps.openstack.utils import (
28 keystone_utils, neutron_utils, nova_utils, cinder_utils)
30 __author__ = 'spisarski'
32 logger = logging.getLogger('heat_utils')
35 def heat_client(os_creds):
37 Retrieves the Heat client
38 :param os_creds: the OpenStack credentials
41 logger.debug('Retrieving Heat Client')
42 return Client(os_creds.heat_api_version,
43 session=keystone_utils.keystone_session(os_creds),
44 region_name=os_creds.region_name)
47 def get_stack(heat_cli, stack_settings=None, stack_name=None):
49 Returns the first domain Stack object found. When stack_setting
50 is not None, the filter created will take the name attribute. When
51 stack_settings is None and stack_name is not, stack_name will be used
52 instead. When both are None, the first stack object received will be
54 :param heat_cli: the OpenStack heat client
55 :param stack_settings: a StackSettings object
56 :param stack_name: the name of the heat stack to return
57 :return: the Stack domain object else None
62 stack_filter['stack_name'] = stack_settings.name
64 stack_filter['stack_name'] = stack_name
66 stacks = heat_cli.stacks.list(**stack_filter)
68 return Stack(name=stack.identifier, stack_id=stack.id)
71 def get_stack_by_id(heat_cli, stack_id):
73 Returns a domain Stack object for a given ID
74 :param heat_cli: the OpenStack heat client
75 :param stack_id: the ID of the heat stack to retrieve
76 :return: the Stack domain object else None
78 stack = heat_cli.stacks.get(stack_id)
79 return Stack(name=stack.identifier, stack_id=stack.id)
82 def get_stack_status(heat_cli, stack_id):
84 Returns the current status of the Heat stack
85 :param heat_cli: the OpenStack heat client
86 :param stack_id: the ID of the heat stack to retrieve
89 return heat_cli.stacks.get(stack_id).stack_status
92 def get_stack_status_reason(heat_cli, stack_id):
94 Returns the current status of the Heat stack
95 :param heat_cli: the OpenStack heat client
96 :param stack_id: the ID of the heat stack to retrieve
97 :return: reason for stack creation failure
99 return heat_cli.stacks.get(stack_id).stack_status_reason
102 def create_stack(heat_cli, stack_settings):
104 Executes an Ansible playbook to the given host
105 :param heat_cli: the OpenStack heat client object
106 :param stack_settings: the stack configuration
107 :return: the Stack domain object
111 if stack_settings.template:
112 args['template'] = stack_settings.template
114 args['template'] = parse_heat_template_str(
115 file_utils.read_file(stack_settings.template_path))
116 args['stack_name'] = stack_settings.name
118 if stack_settings.env_values:
119 args['parameters'] = stack_settings.env_values
121 if stack_settings.resource_files:
123 for res_file in stack_settings.resource_files:
124 heat_resource_contents = file_utils.read_file(res_file)
125 base_filename = os.path.basename(res_file)
127 if heat_resource_contents and base_filename:
128 resources[base_filename] = heat_resource_contents
129 args['files'] = resources
131 stack = heat_cli.stacks.create(**args)
133 return get_stack_by_id(heat_cli, stack_id=stack['stack']['id'])
136 def delete_stack(heat_cli, stack):
138 Deletes the Heat stack
139 :param heat_cli: the OpenStack heat client object
140 :param stack: the OpenStack Heat stack object
142 heat_cli.stacks.delete(stack.id)
145 def __get_os_resources(heat_cli, res_id):
147 Returns all of the OpenStack resource objects for a given stack
148 :param heat_cli: the OpenStack heat client
149 :param res_id: the resource ID
152 return heat_cli.resources.list(res_id)
155 def get_resources(heat_cli, res_id, res_type=None):
157 Returns all of the OpenStack resource objects for a given stack
158 :param heat_cli: the OpenStack heat client
159 :param res_id: the SNAPS-OO Stack domain object
160 :param res_type: the type name to filter
161 :return: a list of Resource domain objects
163 os_resources = __get_os_resources(heat_cli, res_id)
167 for os_resource in os_resources:
168 if ((res_type and os_resource.resource_type == res_type)
171 name=os_resource.resource_name,
172 resource_type=os_resource.resource_type,
173 resource_id=os_resource.physical_resource_id,
174 status=os_resource.resource_status,
175 status_reason=os_resource.resource_status_reason))
179 def get_outputs(heat_cli, stack):
181 Returns all of the SNAPS-OO Output domain objects for the defined outputs
183 :param heat_cli: the OpenStack heat client
184 :param stack: the SNAPS-OO Stack domain object
185 :return: a list of Output domain objects
189 os_stack = heat_cli.stacks.get(stack.id)
193 outputs = os_stack.outputs
196 for output in outputs:
197 out.append(Output(**output))
202 def get_stack_networks(heat_cli, neutron, stack):
204 Returns a list of Network domain objects deployed by this stack
205 :param heat_cli: the OpenStack heat client object
206 :param neutron: the OpenStack neutron client object
207 :param stack: the SNAPS-OO Stack domain object
208 :return: a list of Network objects
212 resources = get_resources(heat_cli, stack.id, 'OS::Neutron::Net')
213 for resource in resources:
214 network = neutron_utils.get_network_by_id(neutron, resource.id)
221 def get_stack_routers(heat_cli, neutron, stack):
223 Returns a list of Network domain objects deployed by this stack
224 :param heat_cli: the OpenStack heat client object
225 :param neutron: the OpenStack neutron client object
226 :param stack: the SNAPS-OO Stack domain object
227 :return: a list of Network objects
231 resources = get_resources(heat_cli, stack.id, 'OS::Neutron::Router')
232 for resource in resources:
233 router = neutron_utils.get_router_by_id(neutron, resource.id)
240 def get_stack_security_groups(heat_cli, neutron, stack):
242 Returns a list of SecurityGroup domain objects deployed by this stack
243 :param heat_cli: the OpenStack heat client object
244 :param neutron: the OpenStack neutron client object
245 :param stack: the SNAPS-OO Stack domain object
246 :return: a list of SecurityGroup objects
250 resources = get_resources(heat_cli, stack.id, 'OS::Neutron::SecurityGroup')
251 for resource in resources:
252 security_group = neutron_utils.get_security_group_by_id(
253 neutron, resource.id)
255 out.append(security_group)
260 def get_stack_servers(heat_cli, nova, neutron, keystone, stack, project_name):
262 Returns a list of VMInst domain objects associated with a Stack
263 :param heat_cli: the OpenStack heat client object
264 :param nova: the OpenStack nova client object
265 :param neutron: the OpenStack neutron client object
266 :param keystone: the OpenStack keystone client object
267 :param stack: the SNAPS-OO Stack domain object
268 :param project_name: the associated project ID
269 :return: a list of VMInst domain objects
273 srvr_res = get_resources(heat_cli, stack.id, 'OS::Nova::Server')
274 for resource in srvr_res:
276 server = nova_utils.get_server_object_by_id(
277 nova, neutron, keystone, resource.id, project_name)
281 logger.warn('VmInst cannot be located with ID %s', resource.id)
283 res_grps = get_resources(heat_cli, stack.id, 'OS::Heat::ResourceGroup')
284 for res_grp in res_grps:
285 res_ress = get_resources(heat_cli, res_grp.id)
286 for res_res in res_ress:
287 res_res_srvrs = get_resources(
288 heat_cli, res_res.id, 'OS::Nova::Server')
289 for res_srvr in res_res_srvrs:
290 server = nova_utils.get_server_object_by_id(
291 nova, neutron, keystone, res_srvr.id, project_name)
298 def get_stack_keypairs(heat_cli, nova, stack):
300 Returns a list of Keypair domain objects associated with a Stack
301 :param heat_cli: the OpenStack heat client object
302 :param nova: the OpenStack nova client object
303 :param stack: the SNAPS-OO Stack domain object
304 :return: a list of VMInst domain objects
308 resources = get_resources(heat_cli, stack.id, 'OS::Nova::KeyPair')
309 for resource in resources:
311 keypair = nova_utils.get_keypair_by_id(nova, resource.id)
315 logger.warn('Keypair cannot be located with ID %s', resource.id)
320 def get_stack_volumes(heat_cli, cinder, stack):
322 Returns an instance of Volume domain objects created by this stack
323 :param heat_cli: the OpenStack heat client object
324 :param cinder: the OpenStack cinder client object
325 :param stack: the SNAPS-OO Stack domain object
326 :return: a list of Volume domain objects
330 resources = get_resources(heat_cli, stack.id, 'OS::Cinder::Volume')
331 for resource in resources:
333 server = cinder_utils.get_volume_by_id(cinder, resource.id)
337 logger.warn('Volume cannot be located with ID %s', resource.id)
342 def get_stack_volume_types(heat_cli, cinder, stack):
344 Returns an instance of VolumeType domain objects created by this stack
345 :param heat_cli: the OpenStack heat client object
346 :param cinder: the OpenStack cinder client object
347 :param stack: the SNAPS-OO Stack domain object
348 :return: a list of VolumeType domain objects
352 resources = get_resources(heat_cli, stack.id, 'OS::Cinder::VolumeType')
353 for resource in resources:
355 vol_type = cinder_utils.get_volume_type_by_id(cinder, resource.id)
359 logger.warn('VolumeType cannot be located with ID %s', resource.id)
364 def get_stack_flavors(heat_cli, nova, stack):
366 Returns an instance of Flavor SNAPS domain object for each flavor created
368 :param heat_cli: the OpenStack heat client object
369 :param nova: the OpenStack cinder client object
370 :param stack: the SNAPS-OO Stack domain object
371 :return: a list of Volume domain objects
375 resources = get_resources(heat_cli, stack.id, 'OS::Nova::Flavor')
376 for resource in resources:
378 flavor = nova_utils.get_flavor_by_id(nova, resource.id)
382 logger.warn('Flavor cannot be located with ID %s', resource.id)
387 def parse_heat_template_str(tmpl_str):
389 Takes a heat template string, performs some simple validation and returns a
390 dict containing the parsed structure. This function supports both JSON and
391 YAML Heat template formats.
393 if tmpl_str.startswith('{'):
394 tpl = jsonutils.loads(tmpl_str)
397 tpl = yaml.load(tmpl_str, Loader=yaml_loader)
398 except yaml.YAMLError as yea:
399 raise ValueError(yea)
403 # Looking for supported version keys in the loaded template
404 if not ('HeatTemplateFormatVersion' in tpl or
405 'heat_template_version' in tpl or
406 'AWSTemplateFormatVersion' in tpl):
407 raise ValueError("Template format version not found.")