1 #############################################################################
2 # Copyright (c) 2015-2017 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
23 from oslo_serialization import jsonutils
24 from oslo_utils import encodeutils
25 from shade._heat import event_utils
27 from yardstick.common import constants as consts
28 from yardstick.common import exceptions
29 from yardstick.common import template_format
30 from yardstick.common import openstack_utils as op_utils
33 log = logging.getLogger(__name__)
36 PROVIDER_SRIOV = "sriov"
41 class HeatStack(object):
42 """Represents a Heat stack (deployed template) """
44 def __init__(self, name, os_cloud_config=None):
47 os_cloud_config = {} if not os_cloud_config else os_cloud_config
48 self._cloud = op_utils.get_shade_client(**os_cloud_config)
51 def _update_stack_tracking(self):
52 outputs = self._stack.outputs
53 self.outputs = {output['output_key']: output['output_value'] for output
56 _DEPLOYED_STACKS[self.uuid] = self._stack
58 def create(self, template, heat_parameters, wait, timeout):
59 """Creates an OpenStack stack from a template"""
60 with tempfile.NamedTemporaryFile('wb', delete=False) as template_file:
61 template_file.write(jsonutils.dump_as_bytes(template))
63 self._stack = self._cloud.create_stack(
64 self.name, template_file=template_file.name, wait=wait,
65 timeout=timeout, **heat_parameters)
67 self._update_stack_tracking()
69 def get_failures(self):
70 return event_utils.get_events(self._cloud, self._stack.id,
71 event_args={'resource_status': 'FAILED'})
74 """Retrieves an existing stack from the target cloud
76 Returns a bool indicating whether the stack exists in the target cloud
77 If the stack exists, it will be stored as self._stack
79 self._stack = self._cloud.get_stack(self.name)
83 self._update_stack_tracking()
88 """Check if any stack has been deployed"""
89 return len(_DEPLOYED_STACKS) > 0
91 def delete(self, wait=True):
92 """Deletes a stack in the target cloud"""
97 ret = self._cloud.delete_stack(self.uuid, wait=wait)
99 # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
100 # tries to retrieve and read the stack status when it's already
104 _DEPLOYED_STACKS.pop(self.uuid)
110 """Delete all deployed stacks"""
111 for stack in _DEPLOYED_STACKS:
116 """Retrieve the current stack status"""
118 return self._stack.status
122 """Retrieve the current stack ID"""
124 return self._stack.id
127 class HeatTemplate(object):
128 """Describes a Heat template and a method to deploy template to a stack"""
130 DESCRIPTION_TEMPLATE = """
131 Stack built by the yardstick framework for %s on host %s %s.
132 All referred generated resources are prefixed with the template
136 HEAT_WAIT_LOOP_INTERVAL = 2
137 HEAT_STATUS_COMPLETE = 'COMPLETE'
139 def _init_template(self):
140 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
142 'heat_template_version': '2013-05-23',
143 'description': self.DESCRIPTION_TEMPLATE % (
145 socket.gethostname(),
153 # short hand for resources part of template
154 self.resources = self._template['resources']
156 def __init__(self, name, template_file=None, heat_parameters=None,
157 os_cloud_config=None):
159 self.keystone_client = None
160 self.heat_parameters = {}
161 self._os_cloud_config = {} if not os_cloud_config else os_cloud_config
163 # heat_parameters is passed to heat in stack create, empty dict when
164 # yardstick creates the template (no get_param in resources part)
166 self.heat_parameters = heat_parameters
169 with open(template_file) as stream:
170 log.info('Parsing external template: %s', template_file)
171 template_str = stream.read()
172 self._template = template_format.parse(template_str)
173 self._parameters = heat_parameters
175 self._init_template()
177 log.debug("template object '%s' created", name)
179 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
180 is_public=True, rxtx_factor=1.0, swap=0,
182 """add to the template a Flavor description"""
185 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
186 "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
187 "swap '%d' extra_specs '%s'",
188 name, vcpus, ram, disk, ephemeral, is_public,
189 rxtx_factor, swap, str(extra_specs))
192 assert isinstance(extra_specs, collections.Mapping)
194 self.resources[name] = {
195 'type': 'OS::Nova::Flavor',
196 'properties': {'name': name,
201 'rxtx_factor': rxtx_factor,
203 'is_public': is_public,
204 'ephemeral': ephemeral,
205 'extra_specs': extra_specs}
208 self._template['outputs'][name] = {
209 'description': 'Flavor %s ID' % name,
210 'value': {'get_resource': name}
213 def add_volume(self, name, size=10):
214 """add to the template a volume description"""
215 log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
217 self.resources[name] = {
218 'type': 'OS::Cinder::Volume',
219 'properties': {'name': name,
223 self._template['outputs'][name] = {
224 'description': 'Volume %s ID' % name,
225 'value': {'get_resource': name}
228 def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
229 """add to the template an association of volume to instance"""
230 log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
233 name = "%s-%s" % (server_name, volume_name)
235 # TODO(elfoley): Fix this on master, it is a bug, and exposes untested
236 # code. Yardstick will crash when heat context uses volume.
237 # pylint: disable=no-value-for-parameter
238 volume_id = op_utils.get_volume_id(volume_name)
239 # pylint: enable=no-value-for-parameter
241 volume_id = {'get_resource': volume_name}
242 self.resources[name] = {
243 'type': 'OS::Cinder::VolumeAttachment',
244 'properties': {'instance_uuid': {'get_resource': server_name},
245 'volume_id': volume_id}
249 self.resources[name]['properties']['mountpoint'] = mountpoint
251 def add_network(self, name, physical_network='physnet1', provider=None,
252 segmentation_id=None, port_security_enabled=None, network_type=None):
253 """add to the template a Neutron Net"""
254 log.debug("adding Neutron::Net '%s'", name)
256 self.resources[name] = {
257 'type': 'OS::Neutron::Net',
263 self.resources[name] = {
264 'type': 'OS::Neutron::ProviderNet',
267 'network_type': 'flat' if network_type is None else network_type,
268 'physical_network': physical_network,
272 self.resources[name]['properties']['segmentation_id'] = segmentation_id
273 if network_type is None:
274 self.resources[name]['properties']['network_type'] = 'vlan'
275 # if port security is not defined then don't add to template:
276 # some deployments don't have port security plugin installed
277 if port_security_enabled is not None:
278 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
280 def add_server_group(self, name, policies): # pragma: no cover
281 """add to the template a ServerGroup"""
282 log.debug("adding Nova::ServerGroup '%s'", name)
283 policies = policies if isinstance(policies, list) else [policies]
284 self.resources[name] = {
285 'type': 'OS::Nova::ServerGroup',
286 'properties': {'name': name,
287 'policies': policies}
290 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
291 """add to the template a Neutron Subnet
293 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
295 self.resources[name] = {
296 'type': 'OS::Neutron::Subnet',
297 'depends_on': network,
301 'network_id': {'get_resource': network},
302 'enable_dhcp': enable_dhcp,
305 if gateway_ip == 'null':
306 self.resources[name]['properties']['gateway_ip'] = None
307 elif gateway_ip is not None:
308 self.resources[name]['properties']['gateway_ip'] = gateway_ip
310 self._template['outputs'][name] = {
311 'description': 'subnet %s ID' % name,
312 'value': {'get_resource': name}
314 self._template['outputs'][name + "-cidr"] = {
315 'description': 'subnet %s cidr' % name,
316 'value': {'get_attr': [name, 'cidr']}
318 self._template['outputs'][name + "-gateway_ip"] = {
319 'description': 'subnet %s gateway_ip' % name,
320 'value': {'get_attr': [name, 'gateway_ip']}
323 def add_router(self, name, ext_gw_net, subnet_name):
324 """add to the template a Neutron Router and interface"""
325 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
326 self.resources[name] = {
327 'type': 'OS::Neutron::Router',
328 'depends_on': [subnet_name],
331 'external_gateway_info': {
332 'network': ext_gw_net
337 def add_router_interface(self, name, router_name, subnet_name):
338 """add to the template a Neutron RouterInterface and interface"""
339 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
340 "subnet:'%s'", name, router_name, subnet_name)
341 self.resources[name] = {
342 'type': 'OS::Neutron::RouterInterface',
343 'depends_on': [router_name, subnet_name],
345 'router_id': {'get_resource': router_name},
346 'subnet_id': {'get_resource': subnet_name}
350 def add_port(self, name, network, sec_group_id=None,
351 provider=None, allowed_address_pairs=None):
352 """add to the template a named Neutron Port
354 net_is_existing = network.net_flags.get(consts.IS_EXISTING)
355 depends_on = [] if net_is_existing else [network.subnet_stack_name]
356 fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
357 {'subnet': {'get_resource': network.subnet_stack_name}}]
358 network_ = network.name if net_is_existing else {
359 'get_resource': network.stack_name}
360 self.resources[name] = {
361 'type': 'OS::Neutron::Port',
362 'depends_on': depends_on,
365 'binding:vnic_type': network.vnic_type,
366 'fixed_ips': fixed_ips,
371 if provider == PROVIDER_SRIOV:
372 self.resources[name]['properties']['binding:vnic_type'] = \
376 self.resources[name]['depends_on'].append(sec_group_id)
377 self.resources[name]['properties']['security_groups'] = \
380 if allowed_address_pairs:
381 self.resources[name]['properties'][
382 'allowed_address_pairs'] = allowed_address_pairs
384 log.debug("adding Neutron::Port %s", self.resources[name])
386 self._template['outputs'][name] = {
387 'description': 'Address for interface %s' % name,
388 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
390 self._template['outputs'][name + "-subnet_id"] = {
391 'description': 'Address for interface %s' % name,
392 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
394 self._template['outputs'][name + "-mac_address"] = {
395 'description': 'MAC Address for interface %s' % name,
396 'value': {'get_attr': [name, 'mac_address']}
398 self._template['outputs'][name + "-device_id"] = {
399 'description': 'Device ID for interface %s' % name,
400 'value': {'get_attr': [name, 'device_id']}
402 self._template['outputs'][name + "-network_id"] = {
403 'description': 'Network ID for interface %s' % name,
404 'value': {'get_attr': [name, 'network_id']}
407 def add_floating_ip(self, name, network_name, port_name, router_if_name,
409 """add to the template a Nova FloatingIP resource
410 see: https://bugs.launchpad.net/heat/+bug/1299259
412 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
413 "rif '%s'", name, network_name, port_name, router_if_name)
415 self.resources[name] = {
416 'type': 'OS::Nova::FloatingIP',
417 'depends_on': [port_name, router_if_name],
424 self.resources[name]["depends_on"].append(secgroup_name)
426 self._template['outputs'][name] = {
427 'description': 'floating ip %s' % name,
428 'value': {'get_attr': [name, 'ip']}
431 def add_floating_ip_association(self, name, floating_ip_name, port_name):
432 """add to the template a Nova FloatingIP Association resource
434 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
435 "floating_ip '%s'", name, port_name, floating_ip_name)
437 self.resources[name] = {
438 'type': 'OS::Neutron::FloatingIPAssociation',
439 'depends_on': [port_name],
441 'floatingip_id': {'get_resource': floating_ip_name},
442 'port_id': {'get_resource': port_name}
446 def add_keypair(self, name, key_id):
447 """add to the template a Nova KeyPair"""
448 log.debug("adding Nova::KeyPair '%s'", name)
449 self.resources[name] = {
450 'type': 'OS::Nova::KeyPair',
453 # resource_string returns bytes, so we must decode to unicode
454 'public_key': encodeutils.safe_decode(
455 pkg_resources.resource_string(
456 'yardstick.resources',
457 'files/yardstick_key-' +
463 def add_servergroup(self, name, policy):
464 """add to the template a Nova ServerGroup"""
465 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
466 if policy not in ["anti-affinity", "affinity"]:
467 raise ValueError(policy)
469 self.resources[name] = {
470 'type': 'OS::Nova::ServerGroup',
477 self._template['outputs'][name] = {
478 'description': 'ID Server Group %s' % name,
479 'value': {'get_resource': name}
482 def add_security_group(self, name, security_group=None):
483 """add to the template a Neutron SecurityGroup"""
484 log.debug("adding Neutron::SecurityGroup '%s'", name)
485 description = ("Group allowing IPv4 and IPv6 for icmp and upd/tcp on"
488 {'remote_ip_prefix': '0.0.0.0/0',
490 'port_range_min': '1',
491 'port_range_max': '65535'},
492 {'remote_ip_prefix': '0.0.0.0/0',
494 'port_range_min': '1',
495 'port_range_max': '65535'},
496 {'remote_ip_prefix': '0.0.0.0/0',
498 {'remote_ip_prefix': '::/0',
501 'port_range_min': '1',
502 'port_range_max': '65535'},
503 {'remote_ip_prefix': '::/0',
506 'port_range_min': '1',
507 'port_range_max': '65535'},
508 {'remote_ip_prefix': '::/0',
510 'protocol': 'ipv6-icmp'},
511 {'remote_ip_prefix': '0.0.0.0/0',
512 'direction': 'egress',
514 'port_range_min': '1',
515 'port_range_max': '65535'},
516 {'remote_ip_prefix': '0.0.0.0/0',
517 'direction': 'egress',
519 'port_range_min': '1',
520 'port_range_max': '65535'},
521 {'remote_ip_prefix': '0.0.0.0/0',
522 'direction': 'egress',
524 {'remote_ip_prefix': '::/0',
525 'direction': 'egress',
528 'port_range_min': '1',
529 'port_range_max': '65535'},
530 {'remote_ip_prefix': '::/0',
531 'direction': 'egress',
534 'port_range_min': '1',
535 'port_range_max': '65535'},
536 {'remote_ip_prefix': '::/0',
537 'direction': 'egress',
539 'protocol': 'ipv6-icmp'},
542 description = "Custom security group rules defined by the user"
543 rules = security_group.get('rules')
545 log.debug("The security group rules is %s", rules)
547 self.resources[name] = {
548 'type': 'OS::Neutron::SecurityGroup',
551 'description': description,
556 self._template['outputs'][name] = {
557 'description': 'ID of Security Group',
558 'value': {'get_resource': name}
561 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
562 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
563 additional_properties=None, availability_zone=None):
564 """add to the template a Nova Server """
565 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
566 "ports %s", name, image, flavor, ports)
568 self.resources[name] = {
569 'type': 'OS::Nova::Server',
573 server_properties = {
577 'networks': [] # list of dictionaries
579 if availability_zone:
580 server_properties["availability_zone"] = availability_zone
582 if flavor in flavors:
583 self.resources[name]['depends_on'].append(flavor)
584 server_properties["flavor"] = {'get_resource': flavor}
586 server_properties["flavor"] = flavor
589 server_properties['admin_user'] = user
592 self.resources[name]['depends_on'].append(key_name)
593 server_properties['key_name'] = {'get_resource': key_name}
596 self.resources[name]['depends_on'].extend(ports)
598 server_properties['networks'].append(
599 {'port': {'get_resource': port}}
603 for i, _ in enumerate(networks):
604 server_properties['networks'].append({'network': networks[i]})
607 server_properties['scheduler_hints'] = scheduler_hints
610 server_properties['user_data'] = user_data
613 assert isinstance(metadata, collections.Mapping)
614 server_properties['metadata'] = metadata
616 if additional_properties:
617 assert isinstance(additional_properties, collections.Mapping)
618 for prop in additional_properties:
619 server_properties[prop] = additional_properties[prop]
621 server_properties['config_drive'] = True
623 self.resources[name]['properties'] = server_properties
625 self._template['outputs'][name] = {
626 'description': 'VM UUID',
627 'value': {'get_resource': name}
630 def create(self, block=True, timeout=3600):
631 """Creates a stack in the target based on the stored template
633 :param block: (bool) Wait for Heat create to finish
634 :param timeout: (int) Timeout in seconds for Heat create,
636 :return A dict with the requested output values from the template
638 log.info("Creating stack '%s' START", self.name)
640 start_time = time.time()
641 stack = HeatStack(self.name, os_cloud_config=self._os_cloud_config)
642 stack.create(self._template, self.heat_parameters, block, timeout)
645 log.info("Creating stack '%s' DONE in %d secs",
646 self.name, time.time() - start_time)
649 if stack.status != self.HEAT_STATUS_COMPLETE:
650 for event in stack.get_failures():
651 log.error("%s", event.resource_status_reason)
652 log.error(pprint.pformat(self._template))
653 raise exceptions.HeatTemplateError(stack_name=self.name)
655 log.info("Creating stack '%s' DONE in %d secs",
656 self.name, time.time() - start_time)