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
26 from oslo_utils import encodeutils
28 import yardstick.common.openstack_utils as op_utils
29 from yardstick.common import template_format
31 log = logging.getLogger(__name__)
34 HEAT_KEY_UUID_LENGTH = 8
36 PROVIDER_SRIOV = "sriov"
39 def get_short_key_uuid(uuid):
40 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
43 class HeatObject(object):
44 """base class for template and stack"""
47 self._heat_client = None
50 def _get_heat_client(self):
51 """returns a heat client instance"""
53 if self._heat_client is None:
54 sess = op_utils.get_session()
55 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
56 self._heat_client = heatclient.client.Client(
57 op_utils.get_heat_api_version(),
58 endpoint=heat_endpoint, session=sess)
60 return self._heat_client
63 """returns stack state as a string"""
64 heat = self._get_heat_client()
65 stack = heat.stacks.get(self.uuid)
66 return getattr(stack, 'stack_status')
69 class HeatStack(HeatObject):
70 """Represents a Heat stack (deployed template) """
73 def __init__(self, name):
74 super(HeatStack, self).__init__()
78 HeatStack.stacks.append(self)
82 """check if any stack has been deployed"""
83 return len(HeatStack.stacks) > 0
86 """deletes a stack from the target cloud using heat"""
90 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
91 heat = self._get_heat_client()
92 template = heat.stacks.get(self.uuid)
93 start_time = time.time()
95 status = self.status()
97 while status != u'DELETE_COMPLETE':
98 log.debug("stack state %s", status)
99 if status == u'DELETE_FAILED':
101 heat.stacks.get(self.uuid).stack_status_reason)
104 status = self.status()
106 end_time = time.time()
107 log.info("Deleted stack '%s' in %d secs", self.name,
108 end_time - start_time)
111 def delete(self, block=True, retries=3):
112 """deletes a stack in the target cloud using heat (with retry)
113 Sometimes delete fail with "InternalServerError" and the next attempt
114 succeeds. So it is worthwhile to test a couple of times.
116 if self.uuid is None:
128 except RuntimeError as err:
129 log.warning(err.args)
133 # if still not deleted try once more and let it fail everything
134 if self.uuid is not None:
137 HeatStack.stacks.remove(self)
141 for stack in HeatStack.stacks[:]:
146 raise RuntimeError("not implemented")
149 class HeatTemplate(HeatObject):
150 """Describes a Heat template and a method to deploy template to a stack"""
152 DESCRIPTION_TEMPLATE = """\
153 Stack built by the yardstick framework for %s on host %s %s.
154 All referred generated resources are prefixed with the template
158 def _init_template(self):
159 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
161 'heat_template_version': '2013-05-23',
162 'description': self.DESCRIPTION_TEMPLATE % (
164 socket.gethostname(),
172 # short hand for resources part of template
173 self.resources = self._template['resources']
175 def __init__(self, name, template_file=None, heat_parameters=None):
176 super(HeatTemplate, self).__init__()
178 self.state = "NOT_CREATED"
179 self.keystone_client = None
180 self.heat_client = None
181 self.heat_parameters = {}
183 # heat_parameters is passed to heat in stack create, empty dict when
184 # yardstick creates the template (no get_param in resources part)
186 self.heat_parameters = heat_parameters
189 with open(template_file) as stream:
190 print("Parsing external template:", template_file)
191 template_str = stream.read()
192 self._template = template_format.parse(template_str)
193 self._parameters = heat_parameters
195 self._init_template()
197 # holds results of requested output after deployment
200 log.debug("template object '%s' created", name)
202 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
203 is_public=True, rxtx_factor=1.0, swap=0,
205 """add to the template a Flavor description"""
208 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' " +
209 "ephemeral '%d' is_public '%s' rxtx_factor '%d' " +
210 "swap '%d' extra_specs '%s' ",
211 name, vcpus, ram, disk, ephemeral, is_public,
212 rxtx_factor, swap, str(extra_specs))
215 assert isinstance(extra_specs, collections.Mapping)
217 self.resources[name] = {
218 'type': 'OS::Nova::Flavor',
219 'properties': {'name': name,
224 'rxtx_factor': rxtx_factor,
226 'is_public': is_public,
227 'ephemeral': ephemeral,
228 'extra_specs': extra_specs}
231 self._template['outputs'][name] = {
232 'description': 'Flavor %s ID' % name,
233 'value': {'get_resource': name}
236 def add_network(self, name, physical_network='physnet1', provider=None):
237 """add to the template a Neutron Net"""
238 log.debug("adding Neutron::Net '%s'", name)
240 self.resources[name] = {
241 'type': 'OS::Neutron::Net',
242 'properties': {'name': name}
245 self.resources[name] = {
246 'type': 'OS::Neutron::ProviderNet',
249 'network_type': 'vlan',
250 'physical_network': physical_network
254 def add_server_group(self, name, policies): # pragma: no cover
255 """add to the template a ServerGroup"""
256 log.debug("adding Nova::ServerGroup '%s'", name)
257 policies = policies if isinstance(policies, list) else [policies]
258 self.resources[name] = {
259 'type': 'OS::Nova::ServerGroup',
260 'properties': {'name': name,
261 'policies': policies}
264 def add_subnet(self, name, network, cidr):
265 """add to the template a Neutron Subnet"""
266 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
268 self.resources[name] = {
269 'type': 'OS::Neutron::Subnet',
270 'depends_on': network,
274 'network_id': {'get_resource': network}
278 self._template['outputs'][name] = {
279 'description': 'subnet %s ID' % name,
280 'value': {'get_resource': name}
283 def add_router(self, name, ext_gw_net, subnet_name):
284 """add to the template a Neutron Router and interface"""
285 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
286 self.resources[name] = {
287 'type': 'OS::Neutron::Router',
288 'depends_on': [subnet_name],
291 'external_gateway_info': {
292 'network': ext_gw_net
297 def add_router_interface(self, name, router_name, subnet_name):
298 """add to the template a Neutron RouterInterface and interface"""
299 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
300 "subnet:'%s'", name, router_name, subnet_name)
301 self.resources[name] = {
302 'type': 'OS::Neutron::RouterInterface',
303 'depends_on': [router_name, subnet_name],
305 'router_id': {'get_resource': router_name},
306 'subnet_id': {'get_resource': subnet_name}
310 def add_port(self, name, network_name, subnet_name, sec_group_id=None,
312 """add to the template a named Neutron Port"""
313 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
314 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
315 self.resources[name] = {
316 'type': 'OS::Neutron::Port',
317 'depends_on': [subnet_name],
320 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
321 'network_id': {'get_resource': network_name},
322 'replacement_policy': 'AUTO',
326 if provider == PROVIDER_SRIOV:
327 self.resources[name]['properties']['binding:vnic_type'] = \
331 self.resources[name]['depends_on'].append(sec_group_id)
332 self.resources[name]['properties']['security_groups'] = \
335 self._template['outputs'][name] = {
336 'description': 'Address for interface %s' % name,
337 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
340 def add_floating_ip(self, name, network_name, port_name, router_if_name,
342 """add to the template a Nova FloatingIP resource
343 see: https://bugs.launchpad.net/heat/+bug/1299259
345 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
346 "rif '%s'", name, network_name, port_name, router_if_name)
348 self.resources[name] = {
349 'type': 'OS::Nova::FloatingIP',
350 'depends_on': [port_name, router_if_name],
357 self.resources[name]["depends_on"].append(secgroup_name)
359 self._template['outputs'][name] = {
360 'description': 'floating ip %s' % name,
361 'value': {'get_attr': [name, 'ip']}
364 def add_floating_ip_association(self, name, floating_ip_name, port_name):
365 """add to the template a Nova FloatingIP Association resource
367 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
368 "floating_ip '%s'", name, port_name, floating_ip_name)
370 self.resources[name] = {
371 'type': 'OS::Neutron::FloatingIPAssociation',
372 'depends_on': [port_name],
374 'floatingip_id': {'get_resource': floating_ip_name},
375 'port_id': {'get_resource': port_name}
379 def add_keypair(self, name, key_uuid):
380 """add to the template a Nova KeyPair"""
381 log.debug("adding Nova::KeyPair '%s'", name)
382 self.resources[name] = {
383 'type': 'OS::Nova::KeyPair',
386 # resource_string returns bytes, so we must decode to unicode
387 'public_key': encodeutils.safe_decode(
388 pkg_resources.resource_string(
389 'yardstick.resources',
390 'files/yardstick_key-' +
391 get_short_key_uuid(key_uuid) + '.pub'),
396 def add_servergroup(self, name, policy):
397 """add to the template a Nova ServerGroup"""
398 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
399 if policy not in ["anti-affinity", "affinity"]:
400 raise ValueError(policy)
402 self.resources[name] = {
403 'type': 'OS::Nova::ServerGroup',
410 self._template['outputs'][name] = {
411 'description': 'ID Server Group %s' % name,
412 'value': {'get_resource': name}
415 def add_security_group(self, name):
416 """add to the template a Neutron SecurityGroup"""
417 log.debug("adding Neutron::SecurityGroup '%s'", name)
418 self.resources[name] = {
419 'type': 'OS::Neutron::SecurityGroup',
422 'description': "Group allowing icmp and upd/tcp on all ports",
424 {'remote_ip_prefix': '0.0.0.0/0',
426 'port_range_min': '1',
427 'port_range_max': '65535'},
428 {'remote_ip_prefix': '0.0.0.0/0',
430 'port_range_min': '1',
431 'port_range_max': '65535'},
432 {'remote_ip_prefix': '0.0.0.0/0',
438 self._template['outputs'][name] = {
439 'description': 'ID of Security Group',
440 'value': {'get_resource': name}
443 def add_server(self, name, image, flavor, flavors, ports=None,
444 networks=None, scheduler_hints=None, user=None,
445 key_name=None, user_data=None, metadata=None,
446 additional_properties=None):
447 """add to the template a Nova Server"""
448 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
449 "ports %s", name, image, flavor, ports)
451 self.resources[name] = {
452 'type': 'OS::Nova::Server',
456 server_properties = {
460 'networks': [] # list of dictionaries
463 if flavor in flavors:
464 self.resources[name]['depends_on'].append(flavor)
465 server_properties["flavor"] = {'get_resource': flavor}
467 server_properties["flavor"] = flavor
470 server_properties['admin_user'] = user
473 self.resources[name]['depends_on'].append(key_name)
474 server_properties['key_name'] = {'get_resource': key_name}
477 self.resources[name]['depends_on'].extend(ports)
479 server_properties['networks'].append(
480 {'port': {'get_resource': port}}
484 for i, _ in enumerate(networks):
485 server_properties['networks'].append({'network': networks[i]})
488 server_properties['scheduler_hints'] = scheduler_hints
491 server_properties['user_data'] = user_data
494 assert isinstance(metadata, collections.Mapping)
495 server_properties['metadata'] = metadata
497 if additional_properties:
498 assert isinstance(additional_properties, collections.Mapping)
499 for prop in additional_properties:
500 server_properties[prop] = additional_properties[prop]
502 server_properties['config_drive'] = True
504 self.resources[name]['properties'] = server_properties
506 self._template['outputs'][name] = {
507 'description': 'VM UUID',
508 'value': {'get_resource': name}
511 def create(self, block=True):
512 """creates a template in the target cloud using heat
513 returns a dict with the requested output values from the template
515 log.info("Creating stack '%s'", self.name)
517 # create stack early to support cleanup, e.g. ctrl-c while waiting
518 stack = HeatStack(self.name)
520 heat = self._get_heat_client()
521 start_time = time.time()
522 stack.uuid = self.uuid = heat.stacks.create(
523 stack_name=self.name, template=self._template,
524 parameters=self.heat_parameters)['stack']['id']
526 status = self.status()
530 while status != u'CREATE_COMPLETE':
531 log.debug("stack state %s", status)
532 if status == u'CREATE_FAILED':
533 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
534 'stack_status_reason'))
537 status = self.status()
539 end_time = time.time()
540 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
541 log.info("Created stack '%s' in %d secs",
542 self.name, end_time - start_time)
544 # keep outputs as unicode
545 self.outputs = {output["output_key"]: output["output_value"] for output
548 stack.outputs = self.outputs