1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
10 """Heat template and stack management"""
20 from oslo_utils import encodeutils
23 from yardstick.common import template_format
24 import yardstick.common.openstack_utils as op_utils
27 log = logging.getLogger(__name__)
30 class HeatObject(object):
31 ''' base class for template and stack'''
33 self._heat_client = None
36 def _get_heat_client(self):
37 '''returns a heat client instance'''
39 if self._heat_client is None:
40 sess = op_utils.get_session()
41 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
42 self._heat_client = heatclient.client.Client(
43 op_utils.get_heat_api_version(),
44 endpoint=heat_endpoint, session=sess)
46 return self._heat_client
49 '''returns stack state as a string'''
50 heat = self._get_heat_client()
51 stack = heat.stacks.get(self.uuid)
52 return getattr(stack, 'stack_status')
55 class HeatStack(HeatObject):
56 ''' Represents a Heat stack (deployed template) '''
59 def __init__(self, name):
60 super(HeatStack, self).__init__()
64 HeatStack.stacks.append(self)
68 '''check if any stack has been deployed'''
69 return len(HeatStack.stacks) > 0
72 '''deletes a stack from the target cloud using heat'''
76 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
77 heat = self._get_heat_client()
78 template = heat.stacks.get(self.uuid)
79 start_time = time.time()
81 status = self.status()
83 while status != u'DELETE_COMPLETE':
84 log.debug("stack state %s", status)
85 if status == u'DELETE_FAILED':
87 heat.stacks.get(self.uuid).stack_status_reason)
90 status = self.status()
92 end_time = time.time()
93 log.info("Deleted stack '%s' in %d secs", self.name,
94 end_time - start_time)
97 def delete(self, block=True, retries=3):
98 '''deletes a stack in the target cloud using heat (with retry)
99 Sometimes delete fail with "InternalServerError" and the next attempt
100 succeeds. So it is worthwhile to test a couple of times.
102 if self.uuid is None:
114 except RuntimeError as err:
119 # if still not deleted try once more and let it fail everything
120 if self.uuid is not None:
123 HeatStack.stacks.remove(self)
127 for stack in HeatStack.stacks[:]:
132 raise RuntimeError("not implemented")
135 class HeatTemplate(HeatObject):
136 '''Describes a Heat template and a method to deploy template to a stack'''
138 def _init_template(self):
140 self._template['heat_template_version'] = '2013-05-23'
142 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
143 self._template['description'] = \
144 '''Stack built by the yardstick framework for %s on host %s %s.
145 All referred generated resources are prefixed with the template
146 name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
147 timestamp, self.name)
149 # short hand for resources part of template
150 self.resources = self._template['resources'] = {}
152 self._template['outputs'] = {}
154 def __init__(self, name, template_file=None, heat_parameters=None):
155 super(HeatTemplate, self).__init__()
157 self.state = "NOT_CREATED"
158 self.keystone_client = None
159 self.heat_client = None
160 self.heat_parameters = {}
162 # heat_parameters is passed to heat in stack create, empty dict when
163 # yardstick creates the template (no get_param in resources part)
165 self.heat_parameters = heat_parameters
168 with open(template_file) as stream:
169 print "Parsing external template:", template_file
170 template_str = stream.read()
171 self._template = template_format.parse(template_str)
172 self._parameters = heat_parameters
174 self._init_template()
176 # holds results of requested output after deployment
179 log.debug("template object '%s' created", name)
181 def add_network(self, name):
182 '''add to the template a Neutron Net'''
183 log.debug("adding Neutron::Net '%s'", name)
184 self.resources[name] = {
185 'type': 'OS::Neutron::Net',
186 'properties': {'name': name}
189 def add_subnet(self, name, network, cidr):
190 '''add to the template a Neutron Subnet'''
191 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
193 self.resources[name] = {
194 'type': 'OS::Neutron::Subnet',
195 'depends_on': network,
199 'network_id': {'get_resource': network}
203 self._template['outputs'][name] = {
204 'description': 'subnet %s ID' % name,
205 'value': {'get_resource': name}
208 def add_router(self, name, ext_gw_net, subnet_name):
209 '''add to the template a Neutron Router and interface'''
210 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
212 self.resources[name] = {
213 'type': 'OS::Neutron::Router',
214 'depends_on': [subnet_name],
217 'external_gateway_info': {
218 'network': ext_gw_net
223 def add_router_interface(self, name, router_name, subnet_name):
224 '''add to the template a Neutron RouterInterface and interface'''
225 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
226 "subnet:'%s'", name, router_name, subnet_name)
228 self.resources[name] = {
229 'type': 'OS::Neutron::RouterInterface',
230 'depends_on': [router_name, subnet_name],
232 'router_id': {'get_resource': router_name},
233 'subnet_id': {'get_resource': subnet_name}
237 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
238 '''add to the template a named Neutron Port'''
239 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
240 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
241 self.resources[name] = {
242 'type': 'OS::Neutron::Port',
243 'depends_on': [subnet_name],
246 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
247 'network_id': {'get_resource': network_name},
248 'replacement_policy': 'AUTO',
253 self.resources[name]['depends_on'].append(sec_group_id)
254 self.resources[name]['properties']['security_groups'] = \
257 self._template['outputs'][name] = {
258 'description': 'Address for interface %s' % name,
259 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
262 def add_floating_ip(self, name, network_name, port_name, router_if_name,
264 '''add to the template a Nova FloatingIP resource
265 see: https://bugs.launchpad.net/heat/+bug/1299259
267 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
268 "rif '%s'", name, network_name, port_name, router_if_name)
270 self.resources[name] = {
271 'type': 'OS::Nova::FloatingIP',
272 'depends_on': [port_name, router_if_name],
279 self.resources[name]["depends_on"].append(secgroup_name)
281 self._template['outputs'][name] = {
282 'description': 'floating ip %s' % name,
283 'value': {'get_attr': [name, 'ip']}
286 def add_floating_ip_association(self, name, floating_ip_name, port_name):
287 '''add to the template a Nova FloatingIP Association resource
289 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
290 "floating_ip '%s'", name, port_name, floating_ip_name)
292 self.resources[name] = {
293 'type': 'OS::Neutron::FloatingIPAssociation',
294 'depends_on': [port_name],
296 'floatingip_id': {'get_resource': floating_ip_name},
297 'port_id': {'get_resource': port_name}
301 def add_keypair(self, name, key_uuid):
302 '''add to the template a Nova KeyPair'''
303 log.debug("adding Nova::KeyPair '%s'", name)
304 self.resources[name] = {
305 'type': 'OS::Nova::KeyPair',
308 'public_key': encodeutils.safe_decode(
309 pkg_resources.resource_string(
310 'yardstick.resources',
311 'files/yardstick_key-{:.{width}}.pub'.format(
317 def add_servergroup(self, name, policy):
318 '''add to the template a Nova ServerGroup'''
319 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
320 if policy not in ["anti-affinity", "affinity"]:
321 raise ValueError(policy)
323 self.resources[name] = {
324 'type': 'OS::Nova::ServerGroup',
331 self._template['outputs'][name] = {
332 'description': 'ID Server Group %s' % name,
333 'value': {'get_resource': name}
336 def add_security_group(self, name):
337 '''add to the template a Neutron SecurityGroup'''
338 log.debug("adding Neutron::SecurityGroup '%s'", name)
339 self.resources[name] = {
340 'type': 'OS::Neutron::SecurityGroup',
343 'description': "Group allowing icmp and upd/tcp on all ports",
345 {'remote_ip_prefix': '0.0.0.0/0',
347 'port_range_min': '1',
348 'port_range_max': '65535'},
349 {'remote_ip_prefix': '0.0.0.0/0',
351 'port_range_min': '1',
352 'port_range_max': '65535'},
353 {'remote_ip_prefix': '0.0.0.0/0',
359 self._template['outputs'][name] = {
360 'description': 'ID of Security Group',
361 'value': {'get_resource': name}
364 def add_server(self, name, image, flavor, ports=None, networks=None,
365 scheduler_hints=None, user=None, key_name=None,
366 user_data=None, metadata=None, additional_properties=None):
367 '''add to the template a Nova Server'''
368 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
369 "ports %s", name, image, flavor, ports)
371 self.resources[name] = {
372 'type': 'OS::Nova::Server'
375 server_properties = {
379 'networks': [] # list of dictionaries
383 server_properties['admin_user'] = user
386 self.resources[name]['depends_on'] = [key_name]
387 server_properties['key_name'] = {'get_resource': key_name}
390 self.resources[name]['depends_on'] = ports
393 server_properties['networks'].append(
394 {'port': {'get_resource': port}}
398 for i in range(len(networks)):
399 server_properties['networks'].append({'network': networks[i]})
402 server_properties['scheduler_hints'] = scheduler_hints
405 server_properties['user_data'] = user_data
408 assert type(metadata) is dict
409 server_properties['metadata'] = metadata
411 if additional_properties:
412 assert type(additional_properties) is dict
413 for prop in additional_properties:
414 server_properties[prop] = additional_properties[prop]
416 server_properties['config_drive'] = True
418 self.resources[name]['properties'] = server_properties
420 self._template['outputs'][name] = {
421 'description': 'VM UUID',
422 'value': {'get_resource': name}
425 def create(self, block=True):
426 '''creates a template in the target cloud using heat
427 returns a dict with the requested output values from the template'''
428 log.info("Creating stack '%s'", self.name)
430 # create stack early to support cleanup, e.g. ctrl-c while waiting
431 stack = HeatStack(self.name)
433 heat = self._get_heat_client()
434 json_template = json.dumps(self._template)
435 start_time = time.time()
436 stack.uuid = self.uuid = heat.stacks.create(
437 stack_name=self.name, template=json_template,
438 parameters=self.heat_parameters)['stack']['id']
440 status = self.status()
443 while status != u'CREATE_COMPLETE':
444 log.debug("stack state %s", status)
445 if status == u'CREATE_FAILED':
446 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
447 'stack_status_reason'))
450 status = self.status()
452 end_time = time.time()
453 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
455 for output in outputs:
456 self.outputs[output["output_key"].encode("ascii")] = \
457 output["output_value"].encode("ascii")
459 log.info("Created stack '%s' in %d secs",
460 self.name, end_time - start_time)
462 stack.outputs = self.outputs