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"""
12 from __future__ import absolute_import
13 from __future__ import print_function
24 from oslo_serialization import jsonutils
25 from oslo_utils import encodeutils
27 import yardstick.common.openstack_utils as op_utils
28 from yardstick.common import template_format
30 log = logging.getLogger(__name__)
33 HEAT_KEY_UUID_LENGTH = 8
36 def get_short_key_uuid(uuid):
37 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
40 class HeatObject(object):
41 """ base class for template and stack"""
44 self._heat_client = None
47 def _get_heat_client(self):
48 """returns a heat client instance"""
50 if self._heat_client is None:
51 sess = op_utils.get_session()
52 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
53 self._heat_client = heatclient.client.Client(
54 op_utils.get_heat_api_version(),
55 endpoint=heat_endpoint, session=sess)
57 return self._heat_client
60 """returns stack state as a string"""
61 heat = self._get_heat_client()
62 stack = heat.stacks.get(self.uuid)
63 return getattr(stack, 'stack_status')
66 class HeatStack(HeatObject):
67 """ Represents a Heat stack (deployed template) """
70 def __init__(self, name):
71 super(HeatStack, self).__init__()
75 HeatStack.stacks.append(self)
79 """check if any stack has been deployed"""
80 return len(HeatStack.stacks) > 0
83 """deletes a stack from the target cloud using heat"""
87 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
88 heat = self._get_heat_client()
89 template = heat.stacks.get(self.uuid)
90 start_time = time.time()
92 status = self.status()
94 while status != u'DELETE_COMPLETE':
95 log.debug("stack state %s", status)
96 if status == u'DELETE_FAILED':
98 heat.stacks.get(self.uuid).stack_status_reason)
101 status = self.status()
103 end_time = time.time()
104 log.info("Deleted stack '%s' in %d secs", self.name,
105 end_time - start_time)
108 def delete(self, block=True, retries=3):
109 """deletes a stack in the target cloud using heat (with retry)
110 Sometimes delete fail with "InternalServerError" and the next attempt
111 succeeds. So it is worthwhile to test a couple of times.
113 if self.uuid is None:
125 except RuntimeError as err:
126 log.warning(err.args)
130 # if still not deleted try once more and let it fail everything
131 if self.uuid is not None:
134 HeatStack.stacks.remove(self)
138 for stack in HeatStack.stacks[:]:
143 raise RuntimeError("not implemented")
146 class HeatTemplate(HeatObject):
147 """Describes a Heat template and a method to deploy template to a stack"""
149 def _init_template(self):
151 self._template['heat_template_version'] = '2013-05-23'
153 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
154 self._template['description'] = \
155 """Stack built by the yardstick framework for %s on host %s %s.
156 All referred generated resources are prefixed with the template
157 name (i.e. %s).""" % (getpass.getuser(), socket.gethostname(),
158 timestamp, self.name)
160 # short hand for resources part of template
161 self.resources = self._template['resources'] = {}
163 self._template['outputs'] = {}
165 def __init__(self, name, template_file=None, heat_parameters=None):
166 super(HeatTemplate, self).__init__()
168 self.state = "NOT_CREATED"
169 self.keystone_client = None
170 self.heat_client = None
171 self.heat_parameters = {}
173 # heat_parameters is passed to heat in stack create, empty dict when
174 # yardstick creates the template (no get_param in resources part)
176 self.heat_parameters = heat_parameters
179 with open(template_file) as stream:
180 print("Parsing external template:", template_file)
181 template_str = stream.read()
182 self._template = template_format.parse(template_str)
183 self._parameters = heat_parameters
185 self._init_template()
187 # holds results of requested output after deployment
190 log.debug("template object '%s' created", name)
192 def add_network(self, name):
193 """add to the template a Neutron Net"""
194 log.debug("adding Neutron::Net '%s'", name)
195 self.resources[name] = {
196 'type': 'OS::Neutron::Net',
197 'properties': {'name': name}
200 def add_subnet(self, name, network, cidr):
201 """add to the template a Neutron Subnet"""
202 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
204 self.resources[name] = {
205 'type': 'OS::Neutron::Subnet',
206 'depends_on': network,
210 'network_id': {'get_resource': network}
214 self._template['outputs'][name] = {
215 'description': 'subnet %s ID' % name,
216 'value': {'get_resource': name}
219 def add_router(self, name, ext_gw_net, subnet_name):
220 """add to the template a Neutron Router and interface"""
221 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
223 self.resources[name] = {
224 'type': 'OS::Neutron::Router',
225 'depends_on': [subnet_name],
228 'external_gateway_info': {
229 'network': ext_gw_net
234 def add_router_interface(self, name, router_name, subnet_name):
235 """add to the template a Neutron RouterInterface and interface"""
236 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
237 "subnet:'%s'", name, router_name, subnet_name)
239 self.resources[name] = {
240 'type': 'OS::Neutron::RouterInterface',
241 'depends_on': [router_name, subnet_name],
243 'router_id': {'get_resource': router_name},
244 'subnet_id': {'get_resource': subnet_name}
248 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
249 """add to the template a named Neutron Port"""
250 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
251 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
252 self.resources[name] = {
253 'type': 'OS::Neutron::Port',
254 'depends_on': [subnet_name],
257 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
258 'network_id': {'get_resource': network_name},
259 'replacement_policy': 'AUTO',
264 self.resources[name]['depends_on'].append(sec_group_id)
265 self.resources[name]['properties']['security_groups'] = \
268 self._template['outputs'][name] = {
269 'description': 'Address for interface %s' % name,
270 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
273 def add_floating_ip(self, name, network_name, port_name, router_if_name,
275 """add to the template a Nova FloatingIP resource
276 see: https://bugs.launchpad.net/heat/+bug/1299259
278 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
279 "rif '%s'", name, network_name, port_name, router_if_name)
281 self.resources[name] = {
282 'type': 'OS::Nova::FloatingIP',
283 'depends_on': [port_name, router_if_name],
290 self.resources[name]["depends_on"].append(secgroup_name)
292 self._template['outputs'][name] = {
293 'description': 'floating ip %s' % name,
294 'value': {'get_attr': [name, 'ip']}
297 def add_floating_ip_association(self, name, floating_ip_name, port_name):
298 """add to the template a Nova FloatingIP Association resource
300 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
301 "floating_ip '%s'", name, port_name, floating_ip_name)
303 self.resources[name] = {
304 'type': 'OS::Neutron::FloatingIPAssociation',
305 'depends_on': [port_name],
307 'floatingip_id': {'get_resource': floating_ip_name},
308 'port_id': {'get_resource': port_name}
312 def add_keypair(self, name, key_uuid):
313 """add to the template a Nova KeyPair"""
314 log.debug("adding Nova::KeyPair '%s'", name)
315 self.resources[name] = {
316 'type': 'OS::Nova::KeyPair',
319 # resource_string returns bytes, so we must decode to unicode
320 'public_key': encodeutils.safe_decode(
321 pkg_resources.resource_string(
322 'yardstick.resources',
323 'files/yardstick_key-' +
324 get_short_key_uuid(key_uuid) + '.pub'),
329 def add_servergroup(self, name, policy):
330 """add to the template a Nova ServerGroup"""
331 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
332 if policy not in ["anti-affinity", "affinity"]:
333 raise ValueError(policy)
335 self.resources[name] = {
336 'type': 'OS::Nova::ServerGroup',
343 self._template['outputs'][name] = {
344 'description': 'ID Server Group %s' % name,
345 'value': {'get_resource': name}
348 def add_security_group(self, name):
349 """add to the template a Neutron SecurityGroup"""
350 log.debug("adding Neutron::SecurityGroup '%s'", name)
351 self.resources[name] = {
352 'type': 'OS::Neutron::SecurityGroup',
355 'description': "Group allowing icmp and upd/tcp on all ports",
357 {'remote_ip_prefix': '0.0.0.0/0',
359 'port_range_min': '1',
360 'port_range_max': '65535'},
361 {'remote_ip_prefix': '0.0.0.0/0',
363 'port_range_min': '1',
364 'port_range_max': '65535'},
365 {'remote_ip_prefix': '0.0.0.0/0',
371 self._template['outputs'][name] = {
372 'description': 'ID of Security Group',
373 'value': {'get_resource': name}
376 def add_server(self, name, image, flavor, ports=None, networks=None,
377 scheduler_hints=None, user=None, key_name=None,
378 user_data=None, metadata=None, additional_properties=None):
379 """add to the template a Nova Server"""
380 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
381 "ports %s", name, image, flavor, ports)
383 self.resources[name] = {
384 'type': 'OS::Nova::Server'
387 server_properties = {
391 'networks': [] # list of dictionaries
395 server_properties['admin_user'] = user
398 self.resources[name]['depends_on'] = [key_name]
399 server_properties['key_name'] = {'get_resource': key_name}
402 self.resources[name]['depends_on'] = ports
405 server_properties['networks'].append(
406 {'port': {'get_resource': port}}
410 for i, _ in enumerate(networks):
411 server_properties['networks'].append({'network': networks[i]})
414 server_properties['scheduler_hints'] = scheduler_hints
417 server_properties['user_data'] = user_data
420 assert isinstance(metadata, collections.Mapping)
421 server_properties['metadata'] = metadata
423 if additional_properties:
424 assert isinstance(additional_properties, collections.Mapping)
425 for prop in additional_properties:
426 server_properties[prop] = additional_properties[prop]
428 server_properties['config_drive'] = True
430 self.resources[name]['properties'] = server_properties
432 self._template['outputs'][name] = {
433 'description': 'VM UUID',
434 'value': {'get_resource': name}
437 def create(self, block=True):
438 """creates a template in the target cloud using heat
439 returns a dict with the requested output values from the template"""
440 log.info("Creating stack '%s'", self.name)
442 # create stack early to support cleanup, e.g. ctrl-c while waiting
443 stack = HeatStack(self.name)
445 heat = self._get_heat_client()
446 json_template = jsonutils.dump_as_bytes(
448 start_time = time.time()
449 stack.uuid = self.uuid = heat.stacks.create(
450 stack_name=self.name, template=json_template,
451 parameters=self.heat_parameters)['stack']['id']
453 status = self.status()
457 while status != u'CREATE_COMPLETE':
458 log.debug("stack state %s", status)
459 if status == u'CREATE_FAILED':
460 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
461 'stack_status_reason'))
464 status = self.status()
466 end_time = time.time()
467 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
468 log.info("Created stack '%s' in %d secs",
469 self.name, end_time - start_time)
471 # keep outputs as unicode
472 self.outputs = {output["output_key"]: output["output_value"] for output
475 stack.outputs = self.outputs