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
34 PROVIDER_SRIOV = "sriov"
37 def get_short_key_uuid(uuid):
38 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
41 class HeatObject(object):
42 """ base class for template and stack"""
45 self._heat_client = None
48 def _get_heat_client(self):
49 """returns a heat client instance"""
51 if self._heat_client is None:
52 sess = op_utils.get_session()
53 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
54 self._heat_client = heatclient.client.Client(
55 op_utils.get_heat_api_version(),
56 endpoint=heat_endpoint, session=sess)
58 return self._heat_client
61 """returns stack state as a string"""
62 heat = self._get_heat_client()
63 stack = heat.stacks.get(self.uuid)
64 return getattr(stack, 'stack_status')
67 class HeatStack(HeatObject):
68 """ Represents a Heat stack (deployed template) """
71 def __init__(self, name):
72 super(HeatStack, self).__init__()
76 HeatStack.stacks.append(self)
80 """check if any stack has been deployed"""
81 return len(HeatStack.stacks) > 0
84 """deletes a stack from the target cloud using heat"""
88 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
89 heat = self._get_heat_client()
90 template = heat.stacks.get(self.uuid)
91 start_time = time.time()
93 status = self.status()
95 while status != u'DELETE_COMPLETE':
96 log.debug("stack state %s", status)
97 if status == u'DELETE_FAILED':
99 heat.stacks.get(self.uuid).stack_status_reason)
102 status = self.status()
104 end_time = time.time()
105 log.info("Deleted stack '%s' in %d secs", self.name,
106 end_time - start_time)
109 def delete(self, block=True, retries=3):
110 """deletes a stack in the target cloud using heat (with retry)
111 Sometimes delete fail with "InternalServerError" and the next attempt
112 succeeds. So it is worthwhile to test a couple of times.
114 if self.uuid is None:
126 except RuntimeError as err:
127 log.warning(err.args)
131 # if still not deleted try once more and let it fail everything
132 if self.uuid is not None:
135 HeatStack.stacks.remove(self)
139 for stack in HeatStack.stacks[:]:
144 raise RuntimeError("not implemented")
147 class HeatTemplate(HeatObject):
148 """Describes a Heat template and a method to deploy template to a stack"""
150 def _init_template(self):
152 self._template['heat_template_version'] = '2013-05-23'
154 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
155 self._template['description'] = \
156 """Stack built by the yardstick framework for %s on host %s %s.
157 All referred generated resources are prefixed with the template
158 name (i.e. %s).""" % (getpass.getuser(), socket.gethostname(),
159 timestamp, self.name)
161 # short hand for resources part of template
162 self.resources = self._template['resources'] = {}
164 self._template['outputs'] = {}
166 def __init__(self, name, template_file=None, heat_parameters=None):
167 super(HeatTemplate, self).__init__()
169 self.state = "NOT_CREATED"
170 self.keystone_client = None
171 self.heat_client = None
172 self.heat_parameters = {}
174 # heat_parameters is passed to heat in stack create, empty dict when
175 # yardstick creates the template (no get_param in resources part)
177 self.heat_parameters = heat_parameters
180 with open(template_file) as stream:
181 print("Parsing external template:", template_file)
182 template_str = stream.read()
183 self._template = template_format.parse(template_str)
184 self._parameters = heat_parameters
186 self._init_template()
188 # holds results of requested output after deployment
191 log.debug("template object '%s' created", name)
193 def add_network(self, name, physical_network='physnet1', provider=None):
194 """add to the template a Neutron Net"""
195 log.debug("adding Neutron::Net '%s'", name)
197 self.resources[name] = {
198 'type': 'OS::Neutron::Net',
199 'properties': {'name': name}
202 self.resources[name] = {
203 'type': 'OS::Neutron::ProviderNet',
206 'network_type': 'vlan',
207 'physical_network': physical_network
211 def add_server_group(self, name, policies): # pragma: no cover
212 """add to the template a ServerGroup"""
213 log.debug("adding Nova::ServerGroup '%s'", name)
214 policies = policies if isinstance(policies, list) else [policies]
215 self.resources[name] = {
216 'type': 'OS::Nova::ServerGroup',
217 'properties': {'name': name,
218 'policies': policies}
221 def add_subnet(self, name, network, cidr):
222 """add to the template a Neutron Subnet"""
223 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
225 self.resources[name] = {
226 'type': 'OS::Neutron::Subnet',
227 'depends_on': network,
231 'network_id': {'get_resource': network}
235 self._template['outputs'][name] = {
236 'description': 'subnet %s ID' % name,
237 'value': {'get_resource': name}
240 def add_router(self, name, ext_gw_net, subnet_name):
241 """add to the template a Neutron Router and interface"""
242 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
243 self.resources[name] = {
244 'type': 'OS::Neutron::Router',
245 'depends_on': [subnet_name],
248 'external_gateway_info': {
249 'network': ext_gw_net
254 def add_router_interface(self, name, router_name, subnet_name):
255 """add to the template a Neutron RouterInterface and interface"""
256 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
257 "subnet:'%s'", name, router_name, subnet_name)
258 self.resources[name] = {
259 'type': 'OS::Neutron::RouterInterface',
260 'depends_on': [router_name, subnet_name],
262 'router_id': {'get_resource': router_name},
263 'subnet_id': {'get_resource': subnet_name}
267 def add_port(self, name, network_name, subnet_name, sec_group_id=None,
269 """add to the template a named Neutron Port"""
270 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
271 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
272 self.resources[name] = {
273 'type': 'OS::Neutron::Port',
274 'depends_on': [subnet_name],
277 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
278 'network_id': {'get_resource': network_name},
279 'replacement_policy': 'AUTO',
283 if provider == PROVIDER_SRIOV:
284 self.resources[name]['properties']['binding:vnic_type'] = \
288 self.resources[name]['depends_on'].append(sec_group_id)
289 self.resources[name]['properties']['security_groups'] = \
292 self._template['outputs'][name] = {
293 'description': 'Address for interface %s' % name,
294 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
297 def add_floating_ip(self, name, network_name, port_name, router_if_name,
299 """add to the template a Nova FloatingIP resource
300 see: https://bugs.launchpad.net/heat/+bug/1299259
302 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
303 "rif '%s'", name, network_name, port_name, router_if_name)
305 self.resources[name] = {
306 'type': 'OS::Nova::FloatingIP',
307 'depends_on': [port_name, router_if_name],
314 self.resources[name]["depends_on"].append(secgroup_name)
316 self._template['outputs'][name] = {
317 'description': 'floating ip %s' % name,
318 'value': {'get_attr': [name, 'ip']}
321 def add_floating_ip_association(self, name, floating_ip_name, port_name):
322 """add to the template a Nova FloatingIP Association resource
324 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
325 "floating_ip '%s'", name, port_name, floating_ip_name)
327 self.resources[name] = {
328 'type': 'OS::Neutron::FloatingIPAssociation',
329 'depends_on': [port_name],
331 'floatingip_id': {'get_resource': floating_ip_name},
332 'port_id': {'get_resource': port_name}
336 def add_keypair(self, name, key_uuid):
337 """add to the template a Nova KeyPair"""
338 log.debug("adding Nova::KeyPair '%s'", name)
339 self.resources[name] = {
340 'type': 'OS::Nova::KeyPair',
343 # resource_string returns bytes, so we must decode to unicode
344 'public_key': encodeutils.safe_decode(
345 pkg_resources.resource_string(
346 'yardstick.resources',
347 'files/yardstick_key-' +
348 get_short_key_uuid(key_uuid) + '.pub'),
353 def add_servergroup(self, name, policy):
354 """add to the template a Nova ServerGroup"""
355 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
356 if policy not in ["anti-affinity", "affinity"]:
357 raise ValueError(policy)
359 self.resources[name] = {
360 'type': 'OS::Nova::ServerGroup',
367 self._template['outputs'][name] = {
368 'description': 'ID Server Group %s' % name,
369 'value': {'get_resource': name}
372 def add_security_group(self, name):
373 """add to the template a Neutron SecurityGroup"""
374 log.debug("adding Neutron::SecurityGroup '%s'", name)
375 self.resources[name] = {
376 'type': 'OS::Neutron::SecurityGroup',
379 'description': "Group allowing icmp and upd/tcp on all ports",
381 {'remote_ip_prefix': '0.0.0.0/0',
383 'port_range_min': '1',
384 'port_range_max': '65535'},
385 {'remote_ip_prefix': '0.0.0.0/0',
387 'port_range_min': '1',
388 'port_range_max': '65535'},
389 {'remote_ip_prefix': '0.0.0.0/0',
395 self._template['outputs'][name] = {
396 'description': 'ID of Security Group',
397 'value': {'get_resource': name}
400 def add_server(self, name, image, flavor, ports=None, networks=None,
401 scheduler_hints=None, user=None, key_name=None,
402 user_data=None, metadata=None, additional_properties=None):
403 """add to the template a Nova Server"""
404 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
405 "ports %s", name, image, flavor, ports)
407 self.resources[name] = {
408 'type': 'OS::Nova::Server'
411 server_properties = {
415 'networks': [] # list of dictionaries
419 server_properties['admin_user'] = user
422 self.resources[name]['depends_on'] = [key_name]
423 server_properties['key_name'] = {'get_resource': key_name}
426 self.resources[name]['depends_on'] = ports
429 server_properties['networks'].append(
430 {'port': {'get_resource': port}}
434 for i, _ in enumerate(networks):
435 server_properties['networks'].append({'network': networks[i]})
438 server_properties['scheduler_hints'] = scheduler_hints
441 server_properties['user_data'] = user_data
444 assert isinstance(metadata, collections.Mapping)
445 server_properties['metadata'] = metadata
447 if additional_properties:
448 assert isinstance(additional_properties, collections.Mapping)
449 for prop in additional_properties:
450 server_properties[prop] = additional_properties[prop]
452 server_properties['config_drive'] = True
454 self.resources[name]['properties'] = server_properties
456 self._template['outputs'][name] = {
457 'description': 'VM UUID',
458 'value': {'get_resource': name}
461 def create(self, block=True):
462 """creates a template in the target cloud using heat
463 returns a dict with the requested output values from the template"""
464 log.info("Creating stack '%s'", self.name)
466 # create stack early to support cleanup, e.g. ctrl-c while waiting
467 stack = HeatStack(self.name)
469 heat = self._get_heat_client()
470 start_time = time.time()
471 stack.uuid = self.uuid = heat.stacks.create(
472 stack_name=self.name, template=self._template,
473 parameters=self.heat_parameters)['stack']['id']
475 status = self.status()
479 while status != u'CREATE_COMPLETE':
480 log.debug("stack state %s", status)
481 if status == u'CREATE_FAILED':
482 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
483 'stack_status_reason'))
486 status = self.status()
488 end_time = time.time()
489 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
490 log.info("Created stack '%s' in %d secs",
491 self.name, end_time - start_time)
493 # keep outputs as unicode
494 self.outputs = {output["output_key"]: output["output_value"] for output
497 stack.outputs = self.outputs