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_utils import encodeutils
26 import yardstick.common.openstack_utils as op_utils
27 from yardstick.common import template_format
29 log = logging.getLogger(__name__)
32 HEAT_KEY_UUID_LENGTH = 8
35 def get_short_key_uuid(uuid):
36 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
39 class HeatObject(object):
40 """ base class for template and stack"""
43 self._heat_client = None
46 def _get_heat_client(self):
47 """returns a heat client instance"""
49 if self._heat_client is None:
50 sess = op_utils.get_session()
51 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
52 self._heat_client = heatclient.client.Client(
53 op_utils.get_heat_api_version(),
54 endpoint=heat_endpoint, session=sess)
56 return self._heat_client
59 """returns stack state as a string"""
60 heat = self._get_heat_client()
61 stack = heat.stacks.get(self.uuid)
62 return getattr(stack, 'stack_status')
65 class HeatStack(HeatObject):
66 """ Represents a Heat stack (deployed template) """
69 def __init__(self, name):
70 super(HeatStack, self).__init__()
74 HeatStack.stacks.append(self)
78 """check if any stack has been deployed"""
79 return len(HeatStack.stacks) > 0
82 """deletes a stack from the target cloud using heat"""
86 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
87 heat = self._get_heat_client()
88 template = heat.stacks.get(self.uuid)
89 start_time = time.time()
91 status = self.status()
93 while status != u'DELETE_COMPLETE':
94 log.debug("stack state %s", status)
95 if status == u'DELETE_FAILED':
97 heat.stacks.get(self.uuid).stack_status_reason)
100 status = self.status()
102 end_time = time.time()
103 log.info("Deleted stack '%s' in %d secs", self.name,
104 end_time - start_time)
107 def delete(self, block=True, retries=3):
108 """deletes a stack in the target cloud using heat (with retry)
109 Sometimes delete fail with "InternalServerError" and the next attempt
110 succeeds. So it is worthwhile to test a couple of times.
112 if self.uuid is None:
124 except RuntimeError as err:
125 log.warning(err.args)
129 # if still not deleted try once more and let it fail everything
130 if self.uuid is not None:
133 HeatStack.stacks.remove(self)
137 for stack in HeatStack.stacks[:]:
142 raise RuntimeError("not implemented")
145 class HeatTemplate(HeatObject):
146 """Describes a Heat template and a method to deploy template to a stack"""
148 def _init_template(self):
150 self._template['heat_template_version'] = '2013-05-23'
152 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
153 self._template['description'] = \
154 """Stack built by the yardstick framework for %s on host %s %s.
155 All referred generated resources are prefixed with the template
156 name (i.e. %s).""" % (getpass.getuser(), socket.gethostname(),
157 timestamp, self.name)
159 # short hand for resources part of template
160 self.resources = self._template['resources'] = {}
162 self._template['outputs'] = {}
164 def __init__(self, name, template_file=None, heat_parameters=None):
165 super(HeatTemplate, self).__init__()
167 self.state = "NOT_CREATED"
168 self.keystone_client = None
169 self.heat_client = None
170 self.heat_parameters = {}
172 # heat_parameters is passed to heat in stack create, empty dict when
173 # yardstick creates the template (no get_param in resources part)
175 self.heat_parameters = heat_parameters
178 with open(template_file) as stream:
179 print("Parsing external template:", template_file)
180 template_str = stream.read()
181 self._template = template_format.parse(template_str)
182 self._parameters = heat_parameters
184 self._init_template()
186 # holds results of requested output after deployment
189 log.debug("template object '%s' created", name)
191 def add_network(self, name):
192 """add to the template a Neutron Net"""
193 log.debug("adding Neutron::Net '%s'", name)
194 self.resources[name] = {
195 'type': 'OS::Neutron::Net',
196 'properties': {'name': name}
199 def add_server_group(self, name, policies): # pragma: no cover
200 """add to the template a ServerGroup"""
201 log.debug("adding Nova::ServerGroup '%s'", name)
202 policies = policies if isinstance(policies, list) else [policies]
203 self.resources[name] = {
204 'type': 'OS::Nova::ServerGroup',
205 'properties': {'name': name,
206 'policies': policies}
209 def add_subnet(self, name, network, cidr):
210 """add to the template a Neutron Subnet"""
211 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
213 self.resources[name] = {
214 'type': 'OS::Neutron::Subnet',
215 'depends_on': network,
219 'network_id': {'get_resource': network}
223 self._template['outputs'][name] = {
224 'description': 'subnet %s ID' % name,
225 'value': {'get_resource': name}
228 def add_router(self, name, ext_gw_net, subnet_name):
229 """add to the template a Neutron Router and interface"""
230 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
232 self.resources[name] = {
233 'type': 'OS::Neutron::Router',
234 'depends_on': [subnet_name],
237 'external_gateway_info': {
238 'network': ext_gw_net
243 def add_router_interface(self, name, router_name, subnet_name):
244 """add to the template a Neutron RouterInterface and interface"""
245 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
246 "subnet:'%s'", name, router_name, subnet_name)
248 self.resources[name] = {
249 'type': 'OS::Neutron::RouterInterface',
250 'depends_on': [router_name, subnet_name],
252 'router_id': {'get_resource': router_name},
253 'subnet_id': {'get_resource': subnet_name}
257 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
258 """add to the template a named Neutron Port"""
259 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
260 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
261 self.resources[name] = {
262 'type': 'OS::Neutron::Port',
263 'depends_on': [subnet_name],
266 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
267 'network_id': {'get_resource': network_name},
268 'replacement_policy': 'AUTO',
273 self.resources[name]['depends_on'].append(sec_group_id)
274 self.resources[name]['properties']['security_groups'] = \
277 self._template['outputs'][name] = {
278 'description': 'Address for interface %s' % name,
279 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
282 def add_floating_ip(self, name, network_name, port_name, router_if_name,
284 """add to the template a Nova FloatingIP resource
285 see: https://bugs.launchpad.net/heat/+bug/1299259
287 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
288 "rif '%s'", name, network_name, port_name, router_if_name)
290 self.resources[name] = {
291 'type': 'OS::Nova::FloatingIP',
292 'depends_on': [port_name, router_if_name],
299 self.resources[name]["depends_on"].append(secgroup_name)
301 self._template['outputs'][name] = {
302 'description': 'floating ip %s' % name,
303 'value': {'get_attr': [name, 'ip']}
306 def add_floating_ip_association(self, name, floating_ip_name, port_name):
307 """add to the template a Nova FloatingIP Association resource
309 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
310 "floating_ip '%s'", name, port_name, floating_ip_name)
312 self.resources[name] = {
313 'type': 'OS::Neutron::FloatingIPAssociation',
314 'depends_on': [port_name],
316 'floatingip_id': {'get_resource': floating_ip_name},
317 'port_id': {'get_resource': port_name}
321 def add_keypair(self, name, key_uuid):
322 """add to the template a Nova KeyPair"""
323 log.debug("adding Nova::KeyPair '%s'", name)
324 self.resources[name] = {
325 'type': 'OS::Nova::KeyPair',
328 # resource_string returns bytes, so we must decode to unicode
329 'public_key': encodeutils.safe_decode(
330 pkg_resources.resource_string(
331 'yardstick.resources',
332 'files/yardstick_key-' +
333 get_short_key_uuid(key_uuid) + '.pub'),
338 def add_servergroup(self, name, policy):
339 """add to the template a Nova ServerGroup"""
340 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
341 if policy not in ["anti-affinity", "affinity"]:
342 raise ValueError(policy)
344 self.resources[name] = {
345 'type': 'OS::Nova::ServerGroup',
352 self._template['outputs'][name] = {
353 'description': 'ID Server Group %s' % name,
354 'value': {'get_resource': name}
357 def add_security_group(self, name):
358 """add to the template a Neutron SecurityGroup"""
359 log.debug("adding Neutron::SecurityGroup '%s'", name)
360 self.resources[name] = {
361 'type': 'OS::Neutron::SecurityGroup',
364 'description': "Group allowing icmp and upd/tcp on all ports",
366 {'remote_ip_prefix': '0.0.0.0/0',
368 'port_range_min': '1',
369 'port_range_max': '65535'},
370 {'remote_ip_prefix': '0.0.0.0/0',
372 'port_range_min': '1',
373 'port_range_max': '65535'},
374 {'remote_ip_prefix': '0.0.0.0/0',
380 self._template['outputs'][name] = {
381 'description': 'ID of Security Group',
382 'value': {'get_resource': name}
385 def add_server(self, name, image, flavor, ports=None, networks=None,
386 scheduler_hints=None, user=None, key_name=None,
387 user_data=None, metadata=None, additional_properties=None):
388 """add to the template a Nova Server"""
389 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
390 "ports %s", name, image, flavor, ports)
392 self.resources[name] = {
393 'type': 'OS::Nova::Server'
396 server_properties = {
400 'networks': [] # list of dictionaries
404 server_properties['admin_user'] = user
407 self.resources[name]['depends_on'] = [key_name]
408 server_properties['key_name'] = {'get_resource': key_name}
411 self.resources[name]['depends_on'] = ports
414 server_properties['networks'].append(
415 {'port': {'get_resource': port}}
419 for i, _ in enumerate(networks):
420 server_properties['networks'].append({'network': networks[i]})
423 server_properties['scheduler_hints'] = scheduler_hints
426 server_properties['user_data'] = user_data
429 assert isinstance(metadata, collections.Mapping)
430 server_properties['metadata'] = metadata
432 if additional_properties:
433 assert isinstance(additional_properties, collections.Mapping)
434 for prop in additional_properties:
435 server_properties[prop] = additional_properties[prop]
437 server_properties['config_drive'] = True
439 self.resources[name]['properties'] = server_properties
441 self._template['outputs'][name] = {
442 'description': 'VM UUID',
443 'value': {'get_resource': name}
446 def create(self, block=True):
447 """creates a template in the target cloud using heat
448 returns a dict with the requested output values from the template"""
449 log.info("Creating stack '%s'", self.name)
451 # create stack early to support cleanup, e.g. ctrl-c while waiting
452 stack = HeatStack(self.name)
454 heat = self._get_heat_client()
455 start_time = time.time()
456 stack.uuid = self.uuid = heat.stacks.create(
457 stack_name=self.name, template=self._template,
458 parameters=self.heat_parameters)['stack']['id']
460 status = self.status()
464 while status != u'CREATE_COMPLETE':
465 log.debug("stack state %s", status)
466 if status == u'CREATE_FAILED':
467 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
468 'stack_status_reason'))
471 status = self.status()
473 end_time = time.time()
474 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
475 log.info("Created stack '%s' in %d secs",
476 self.name, end_time - start_time)
478 # keep outputs as unicode
479 self.outputs = {output["output_key"]: output["output_value"] for output
482 stack.outputs = self.outputs