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 volume_id = op_utils.get_volume_id(volume_name)
237 volume_id = {'get_resource': volume_name}
238 self.resources[name] = {
239 'type': 'OS::Cinder::VolumeAttachment',
240 'properties': {'instance_uuid': {'get_resource': server_name},
241 'volume_id': volume_id}
245 self.resources[name]['properties']['mountpoint'] = mountpoint
247 def add_network(self, name, physical_network='physnet1', provider=None,
248 segmentation_id=None, port_security_enabled=None, network_type=None):
249 """add to the template a Neutron Net"""
250 log.debug("adding Neutron::Net '%s'", name)
252 self.resources[name] = {
253 'type': 'OS::Neutron::Net',
259 self.resources[name] = {
260 'type': 'OS::Neutron::ProviderNet',
263 'network_type': 'flat' if network_type is None else network_type,
264 'physical_network': physical_network,
268 self.resources[name]['properties']['segmentation_id'] = segmentation_id
269 if network_type is None:
270 self.resources[name]['properties']['network_type'] = 'vlan'
271 # if port security is not defined then don't add to template:
272 # some deployments don't have port security plugin installed
273 if port_security_enabled is not None:
274 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
276 def add_server_group(self, name, policies): # pragma: no cover
277 """add to the template a ServerGroup"""
278 log.debug("adding Nova::ServerGroup '%s'", name)
279 policies = policies if isinstance(policies, list) else [policies]
280 self.resources[name] = {
281 'type': 'OS::Nova::ServerGroup',
282 'properties': {'name': name,
283 'policies': policies}
286 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
287 """add to the template a Neutron Subnet
289 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
291 self.resources[name] = {
292 'type': 'OS::Neutron::Subnet',
293 'depends_on': network,
297 'network_id': {'get_resource': network},
298 'enable_dhcp': enable_dhcp,
301 if gateway_ip == 'null':
302 self.resources[name]['properties']['gateway_ip'] = None
303 elif gateway_ip is not None:
304 self.resources[name]['properties']['gateway_ip'] = gateway_ip
306 self._template['outputs'][name] = {
307 'description': 'subnet %s ID' % name,
308 'value': {'get_resource': name}
310 self._template['outputs'][name + "-cidr"] = {
311 'description': 'subnet %s cidr' % name,
312 'value': {'get_attr': [name, 'cidr']}
314 self._template['outputs'][name + "-gateway_ip"] = {
315 'description': 'subnet %s gateway_ip' % name,
316 'value': {'get_attr': [name, 'gateway_ip']}
319 def add_router(self, name, ext_gw_net, subnet_name):
320 """add to the template a Neutron Router and interface"""
321 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
322 self.resources[name] = {
323 'type': 'OS::Neutron::Router',
324 'depends_on': [subnet_name],
327 'external_gateway_info': {
328 'network': ext_gw_net
333 def add_router_interface(self, name, router_name, subnet_name):
334 """add to the template a Neutron RouterInterface and interface"""
335 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
336 "subnet:'%s'", name, router_name, subnet_name)
337 self.resources[name] = {
338 'type': 'OS::Neutron::RouterInterface',
339 'depends_on': [router_name, subnet_name],
341 'router_id': {'get_resource': router_name},
342 'subnet_id': {'get_resource': subnet_name}
346 def add_port(self, name, network, sec_group_id=None,
347 provider=None, allowed_address_pairs=None):
348 """add to the template a named Neutron Port
350 net_is_existing = network.net_flags.get(consts.IS_EXISTING)
351 depends_on = [] if net_is_existing else [network.subnet_stack_name]
352 fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
353 {'subnet': {'get_resource': network.subnet_stack_name}}]
354 network_ = network.name if net_is_existing else {
355 'get_resource': network.stack_name}
356 self.resources[name] = {
357 'type': 'OS::Neutron::Port',
358 'depends_on': depends_on,
361 'binding:vnic_type': network.vnic_type,
362 'fixed_ips': fixed_ips,
367 if provider == PROVIDER_SRIOV:
368 self.resources[name]['properties']['binding:vnic_type'] = \
372 self.resources[name]['depends_on'].append(sec_group_id)
373 self.resources[name]['properties']['security_groups'] = \
376 if allowed_address_pairs:
377 self.resources[name]['properties'][
378 'allowed_address_pairs'] = allowed_address_pairs
380 log.debug("adding Neutron::Port %s", self.resources[name])
382 self._template['outputs'][name] = {
383 'description': 'Address for interface %s' % name,
384 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
386 self._template['outputs'][name + "-subnet_id"] = {
387 'description': 'Address for interface %s' % name,
388 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
390 self._template['outputs'][name + "-mac_address"] = {
391 'description': 'MAC Address for interface %s' % name,
392 'value': {'get_attr': [name, 'mac_address']}
394 self._template['outputs'][name + "-device_id"] = {
395 'description': 'Device ID for interface %s' % name,
396 'value': {'get_attr': [name, 'device_id']}
398 self._template['outputs'][name + "-network_id"] = {
399 'description': 'Network ID for interface %s' % name,
400 'value': {'get_attr': [name, 'network_id']}
403 def add_floating_ip(self, name, network_name, port_name, router_if_name,
405 """add to the template a Nova FloatingIP resource
406 see: https://bugs.launchpad.net/heat/+bug/1299259
408 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
409 "rif '%s'", name, network_name, port_name, router_if_name)
411 self.resources[name] = {
412 'type': 'OS::Nova::FloatingIP',
413 'depends_on': [port_name, router_if_name],
420 self.resources[name]["depends_on"].append(secgroup_name)
422 self._template['outputs'][name] = {
423 'description': 'floating ip %s' % name,
424 'value': {'get_attr': [name, 'ip']}
427 def add_floating_ip_association(self, name, floating_ip_name, port_name):
428 """add to the template a Nova FloatingIP Association resource
430 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
431 "floating_ip '%s'", name, port_name, floating_ip_name)
433 self.resources[name] = {
434 'type': 'OS::Neutron::FloatingIPAssociation',
435 'depends_on': [port_name],
437 'floatingip_id': {'get_resource': floating_ip_name},
438 'port_id': {'get_resource': port_name}
442 def add_keypair(self, name, key_id):
443 """add to the template a Nova KeyPair"""
444 log.debug("adding Nova::KeyPair '%s'", name)
445 self.resources[name] = {
446 'type': 'OS::Nova::KeyPair',
449 # resource_string returns bytes, so we must decode to unicode
450 'public_key': encodeutils.safe_decode(
451 pkg_resources.resource_string(
452 'yardstick.resources',
453 'files/yardstick_key-' +
459 def add_servergroup(self, name, policy):
460 """add to the template a Nova ServerGroup"""
461 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
462 if policy not in ["anti-affinity", "affinity"]:
463 raise ValueError(policy)
465 self.resources[name] = {
466 'type': 'OS::Nova::ServerGroup',
473 self._template['outputs'][name] = {
474 'description': 'ID Server Group %s' % name,
475 'value': {'get_resource': name}
478 def add_security_group(self, name):
479 """add to the template a Neutron SecurityGroup"""
480 log.debug("adding Neutron::SecurityGroup '%s'", name)
481 self.resources[name] = {
482 'type': 'OS::Neutron::SecurityGroup',
485 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
487 {'remote_ip_prefix': '0.0.0.0/0',
489 'port_range_min': '1',
490 'port_range_max': '65535'},
491 {'remote_ip_prefix': '0.0.0.0/0',
493 'port_range_min': '1',
494 'port_range_max': '65535'},
495 {'remote_ip_prefix': '0.0.0.0/0',
497 {'remote_ip_prefix': '::/0',
500 'port_range_min': '1',
501 'port_range_max': '65535'},
502 {'remote_ip_prefix': '::/0',
505 'port_range_min': '1',
506 'port_range_max': '65535'},
507 {'remote_ip_prefix': '::/0',
509 'protocol': 'ipv6-icmp'},
510 {'remote_ip_prefix': '0.0.0.0/0',
511 'direction': 'egress',
513 'port_range_min': '1',
514 'port_range_max': '65535'},
515 {'remote_ip_prefix': '0.0.0.0/0',
516 'direction': 'egress',
518 'port_range_min': '1',
519 'port_range_max': '65535'},
520 {'remote_ip_prefix': '0.0.0.0/0',
521 'direction': 'egress',
523 {'remote_ip_prefix': '::/0',
524 'direction': 'egress',
527 'port_range_min': '1',
528 'port_range_max': '65535'},
529 {'remote_ip_prefix': '::/0',
530 'direction': 'egress',
533 'port_range_min': '1',
534 'port_range_max': '65535'},
535 {'remote_ip_prefix': '::/0',
536 'direction': 'egress',
538 'protocol': 'ipv6-icmp'},
543 self._template['outputs'][name] = {
544 'description': 'ID of Security Group',
545 'value': {'get_resource': name}
548 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
549 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
550 additional_properties=None, availability_zone=None):
551 """add to the template a Nova Server """
552 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
553 "ports %s", name, image, flavor, ports)
555 self.resources[name] = {
556 'type': 'OS::Nova::Server',
560 server_properties = {
564 'networks': [] # list of dictionaries
566 if availability_zone:
567 server_properties["availability_zone"] = availability_zone
569 if flavor in flavors:
570 self.resources[name]['depends_on'].append(flavor)
571 server_properties["flavor"] = {'get_resource': flavor}
573 server_properties["flavor"] = flavor
576 server_properties['admin_user'] = user
579 self.resources[name]['depends_on'].append(key_name)
580 server_properties['key_name'] = {'get_resource': key_name}
583 self.resources[name]['depends_on'].extend(ports)
585 server_properties['networks'].append(
586 {'port': {'get_resource': port}}
590 for i, _ in enumerate(networks):
591 server_properties['networks'].append({'network': networks[i]})
594 server_properties['scheduler_hints'] = scheduler_hints
597 server_properties['user_data'] = user_data
600 assert isinstance(metadata, collections.Mapping)
601 server_properties['metadata'] = metadata
603 if additional_properties:
604 assert isinstance(additional_properties, collections.Mapping)
605 for prop in additional_properties:
606 server_properties[prop] = additional_properties[prop]
608 server_properties['config_drive'] = True
610 self.resources[name]['properties'] = server_properties
612 self._template['outputs'][name] = {
613 'description': 'VM UUID',
614 'value': {'get_resource': name}
617 def create(self, block=True, timeout=3600):
618 """Creates a stack in the target based on the stored template
620 :param block: (bool) Wait for Heat create to finish
621 :param timeout: (int) Timeout in seconds for Heat create,
623 :return A dict with the requested output values from the template
625 log.info("Creating stack '%s' START", self.name)
627 start_time = time.time()
628 stack = HeatStack(self.name, os_cloud_config=self._os_cloud_config)
629 stack.create(self._template, self.heat_parameters, block, timeout)
632 log.info("Creating stack '%s' DONE in %d secs",
633 self.name, time.time() - start_time)
636 if stack.status != self.HEAT_STATUS_COMPLETE:
637 for event in stack.get_failures():
638 log.error("%s", event.resource_status_reason)
639 log.error(pprint.pformat(self._template))
640 raise exceptions.HeatTemplateError(stack_name=self.name)
642 log.info("Creating stack '%s' DONE in %d secs",
643 self.name, time.time() - start_time)