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
26 from shade._heat import event_utils
28 import yardstick.common.openstack_utils as op_utils
29 from yardstick.common import exceptions
30 from yardstick.common import template_format
31 from yardstick.common import constants as consts
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):
47 self._cloud = shade.openstack_cloud()
50 def _update_stack_tracking(self):
51 outputs = self._stack.outputs
52 self.outputs = {output['output_key']: output['output_value'] for output
55 _DEPLOYED_STACKS[self.uuid] = self._stack
57 def create(self, template, heat_parameters, wait, timeout):
58 """Creates an OpenStack stack from a template"""
59 with tempfile.NamedTemporaryFile('wb', delete=False) as template_file:
60 template_file.write(jsonutils.dump_as_bytes(template))
62 self._stack = self._cloud.create_stack(
63 self.name, template_file=template_file.name, wait=wait,
64 timeout=timeout, **heat_parameters)
66 self._update_stack_tracking()
68 def get_failures(self):
69 return event_utils.get_events(self._cloud, self._stack.id,
70 event_args={'resource_status': 'FAILED'})
73 """Retrieves an existing stack from the target cloud
75 Returns a bool indicating whether the stack exists in the target cloud
76 If the stack exists, it will be stored as self._stack
78 self._stack = self._cloud.get_stack(self.name)
82 self._update_stack_tracking()
87 """Check if any stack has been deployed"""
88 return len(_DEPLOYED_STACKS) > 0
90 def delete(self, wait=True):
91 """Deletes a stack in the target cloud"""
96 ret = self._cloud.delete_stack(self.uuid, wait=wait)
98 # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
99 # tries to retrieve and read the stack status when it's already
103 _DEPLOYED_STACKS.pop(self.uuid)
109 """Delete all deployed stacks"""
110 for stack in _DEPLOYED_STACKS:
115 """Retrieve the current stack status"""
117 return self._stack.status
121 """Retrieve the current stack ID"""
123 return self._stack.id
126 class HeatTemplate(object):
127 """Describes a Heat template and a method to deploy template to a stack"""
129 DESCRIPTION_TEMPLATE = """
130 Stack built by the yardstick framework for %s on host %s %s.
131 All referred generated resources are prefixed with the template
135 HEAT_WAIT_LOOP_INTERVAL = 2
136 HEAT_STATUS_COMPLETE = 'COMPLETE'
138 def _init_template(self):
139 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
141 'heat_template_version': '2013-05-23',
142 'description': self.DESCRIPTION_TEMPLATE % (
144 socket.gethostname(),
152 # short hand for resources part of template
153 self.resources = self._template['resources']
155 def __init__(self, name, template_file=None, heat_parameters=None):
157 self.keystone_client = None
158 self.heat_parameters = {}
160 # heat_parameters is passed to heat in stack create, empty dict when
161 # yardstick creates the template (no get_param in resources part)
163 self.heat_parameters = heat_parameters
166 with open(template_file) as stream:
167 log.info('Parsing external template: %s', template_file)
168 template_str = stream.read()
169 self._template = template_format.parse(template_str)
170 self._parameters = heat_parameters
172 self._init_template()
174 log.debug("template object '%s' created", name)
176 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
177 is_public=True, rxtx_factor=1.0, swap=0,
179 """add to the template a Flavor description"""
182 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
183 "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
184 "swap '%d' extra_specs '%s'",
185 name, vcpus, ram, disk, ephemeral, is_public,
186 rxtx_factor, swap, str(extra_specs))
189 assert isinstance(extra_specs, collections.Mapping)
191 self.resources[name] = {
192 'type': 'OS::Nova::Flavor',
193 'properties': {'name': name,
198 'rxtx_factor': rxtx_factor,
200 'is_public': is_public,
201 'ephemeral': ephemeral,
202 'extra_specs': extra_specs}
205 self._template['outputs'][name] = {
206 'description': 'Flavor %s ID' % name,
207 'value': {'get_resource': name}
210 def add_volume(self, name, size=10):
211 """add to the template a volume description"""
212 log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
214 self.resources[name] = {
215 'type': 'OS::Cinder::Volume',
216 'properties': {'name': name,
220 self._template['outputs'][name] = {
221 'description': 'Volume %s ID' % name,
222 'value': {'get_resource': name}
225 def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
226 """add to the template an association of volume to instance"""
227 log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
230 name = "%s-%s" % (server_name, volume_name)
232 volume_id = op_utils.get_volume_id(volume_name)
234 volume_id = {'get_resource': volume_name}
235 self.resources[name] = {
236 'type': 'OS::Cinder::VolumeAttachment',
237 'properties': {'instance_uuid': {'get_resource': server_name},
238 'volume_id': volume_id}
242 self.resources[name]['properties']['mountpoint'] = mountpoint
244 def add_network(self, name, physical_network='physnet1', provider=None,
245 segmentation_id=None, port_security_enabled=None, network_type=None):
246 """add to the template a Neutron Net"""
247 log.debug("adding Neutron::Net '%s'", name)
249 self.resources[name] = {
250 'type': 'OS::Neutron::Net',
256 self.resources[name] = {
257 'type': 'OS::Neutron::ProviderNet',
260 'network_type': 'flat' if network_type is None else network_type,
261 'physical_network': physical_network,
265 self.resources[name]['properties']['segmentation_id'] = segmentation_id
266 if network_type is None:
267 self.resources[name]['properties']['network_type'] = 'vlan'
268 # if port security is not defined then don't add to template:
269 # some deployments don't have port security plugin installed
270 if port_security_enabled is not None:
271 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
273 def add_server_group(self, name, policies): # pragma: no cover
274 """add to the template a ServerGroup"""
275 log.debug("adding Nova::ServerGroup '%s'", name)
276 policies = policies if isinstance(policies, list) else [policies]
277 self.resources[name] = {
278 'type': 'OS::Nova::ServerGroup',
279 'properties': {'name': name,
280 'policies': policies}
283 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
284 """add to the template a Neutron Subnet
286 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
288 self.resources[name] = {
289 'type': 'OS::Neutron::Subnet',
290 'depends_on': network,
294 'network_id': {'get_resource': network},
295 'enable_dhcp': enable_dhcp,
298 if gateway_ip == 'null':
299 self.resources[name]['properties']['gateway_ip'] = None
300 elif gateway_ip is not None:
301 self.resources[name]['properties']['gateway_ip'] = gateway_ip
303 self._template['outputs'][name] = {
304 'description': 'subnet %s ID' % name,
305 'value': {'get_resource': name}
307 self._template['outputs'][name + "-cidr"] = {
308 'description': 'subnet %s cidr' % name,
309 'value': {'get_attr': [name, 'cidr']}
311 self._template['outputs'][name + "-gateway_ip"] = {
312 'description': 'subnet %s gateway_ip' % name,
313 'value': {'get_attr': [name, 'gateway_ip']}
316 def add_router(self, name, ext_gw_net, subnet_name):
317 """add to the template a Neutron Router and interface"""
318 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
319 self.resources[name] = {
320 'type': 'OS::Neutron::Router',
321 'depends_on': [subnet_name],
324 'external_gateway_info': {
325 'network': ext_gw_net
330 def add_router_interface(self, name, router_name, subnet_name):
331 """add to the template a Neutron RouterInterface and interface"""
332 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
333 "subnet:'%s'", name, router_name, subnet_name)
334 self.resources[name] = {
335 'type': 'OS::Neutron::RouterInterface',
336 'depends_on': [router_name, subnet_name],
338 'router_id': {'get_resource': router_name},
339 'subnet_id': {'get_resource': subnet_name}
343 def add_port(self, name, network, sec_group_id=None,
344 provider=None, allowed_address_pairs=None):
345 """add to the template a named Neutron Port
347 net_is_existing = network.net_flags.get(consts.IS_EXISTING)
348 depends_on = [] if net_is_existing else [network.subnet_stack_name]
349 fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
350 {'subnet': {'get_resource': network.subnet_stack_name}}]
351 network_ = network.name if net_is_existing else {
352 'get_resource': network.stack_name}
353 self.resources[name] = {
354 'type': 'OS::Neutron::Port',
355 'depends_on': depends_on,
358 'binding:vnic_type': network.vnic_type,
359 'fixed_ips': fixed_ips,
364 if provider == PROVIDER_SRIOV:
365 self.resources[name]['properties']['binding:vnic_type'] = \
369 self.resources[name]['depends_on'].append(sec_group_id)
370 self.resources[name]['properties']['security_groups'] = \
373 if allowed_address_pairs:
374 self.resources[name]['properties'][
375 'allowed_address_pairs'] = allowed_address_pairs
377 log.debug("adding Neutron::Port %s", self.resources[name])
379 self._template['outputs'][name] = {
380 'description': 'Address for interface %s' % name,
381 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
383 self._template['outputs'][name + "-subnet_id"] = {
384 'description': 'Address for interface %s' % name,
385 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
387 self._template['outputs'][name + "-mac_address"] = {
388 'description': 'MAC Address for interface %s' % name,
389 'value': {'get_attr': [name, 'mac_address']}
391 self._template['outputs'][name + "-device_id"] = {
392 'description': 'Device ID for interface %s' % name,
393 'value': {'get_attr': [name, 'device_id']}
395 self._template['outputs'][name + "-network_id"] = {
396 'description': 'Network ID for interface %s' % name,
397 'value': {'get_attr': [name, 'network_id']}
400 def add_floating_ip(self, name, network_name, port_name, router_if_name,
402 """add to the template a Nova FloatingIP resource
403 see: https://bugs.launchpad.net/heat/+bug/1299259
405 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
406 "rif '%s'", name, network_name, port_name, router_if_name)
408 self.resources[name] = {
409 'type': 'OS::Nova::FloatingIP',
410 'depends_on': [port_name, router_if_name],
417 self.resources[name]["depends_on"].append(secgroup_name)
419 self._template['outputs'][name] = {
420 'description': 'floating ip %s' % name,
421 'value': {'get_attr': [name, 'ip']}
424 def add_floating_ip_association(self, name, floating_ip_name, port_name):
425 """add to the template a Nova FloatingIP Association resource
427 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
428 "floating_ip '%s'", name, port_name, floating_ip_name)
430 self.resources[name] = {
431 'type': 'OS::Neutron::FloatingIPAssociation',
432 'depends_on': [port_name],
434 'floatingip_id': {'get_resource': floating_ip_name},
435 'port_id': {'get_resource': port_name}
439 def add_keypair(self, name, key_id):
440 """add to the template a Nova KeyPair"""
441 log.debug("adding Nova::KeyPair '%s'", name)
442 self.resources[name] = {
443 'type': 'OS::Nova::KeyPair',
446 # resource_string returns bytes, so we must decode to unicode
447 'public_key': encodeutils.safe_decode(
448 pkg_resources.resource_string(
449 'yardstick.resources',
450 'files/yardstick_key-' +
456 def add_servergroup(self, name, policy):
457 """add to the template a Nova ServerGroup"""
458 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
459 if policy not in ["anti-affinity", "affinity"]:
460 raise ValueError(policy)
462 self.resources[name] = {
463 'type': 'OS::Nova::ServerGroup',
470 self._template['outputs'][name] = {
471 'description': 'ID Server Group %s' % name,
472 'value': {'get_resource': name}
475 def add_security_group(self, name):
476 """add to the template a Neutron SecurityGroup"""
477 log.debug("adding Neutron::SecurityGroup '%s'", name)
478 self.resources[name] = {
479 'type': 'OS::Neutron::SecurityGroup',
482 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
484 {'remote_ip_prefix': '0.0.0.0/0',
486 'port_range_min': '1',
487 'port_range_max': '65535'},
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 {'remote_ip_prefix': '::/0',
497 'port_range_min': '1',
498 'port_range_max': '65535'},
499 {'remote_ip_prefix': '::/0',
502 'port_range_min': '1',
503 'port_range_max': '65535'},
504 {'remote_ip_prefix': '::/0',
506 'protocol': 'ipv6-icmp'},
507 {'remote_ip_prefix': '0.0.0.0/0',
508 'direction': 'egress',
510 'port_range_min': '1',
511 'port_range_max': '65535'},
512 {'remote_ip_prefix': '0.0.0.0/0',
513 'direction': 'egress',
515 'port_range_min': '1',
516 'port_range_max': '65535'},
517 {'remote_ip_prefix': '0.0.0.0/0',
518 'direction': 'egress',
520 {'remote_ip_prefix': '::/0',
521 'direction': 'egress',
524 'port_range_min': '1',
525 'port_range_max': '65535'},
526 {'remote_ip_prefix': '::/0',
527 'direction': 'egress',
530 'port_range_min': '1',
531 'port_range_max': '65535'},
532 {'remote_ip_prefix': '::/0',
533 'direction': 'egress',
535 'protocol': 'ipv6-icmp'},
540 self._template['outputs'][name] = {
541 'description': 'ID of Security Group',
542 'value': {'get_resource': name}
545 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
546 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
547 additional_properties=None, availability_zone=None):
548 """add to the template a Nova Server """
549 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
550 "ports %s", name, image, flavor, ports)
552 self.resources[name] = {
553 'type': 'OS::Nova::Server',
557 server_properties = {
561 'networks': [] # list of dictionaries
563 if availability_zone:
564 server_properties["availability_zone"] = availability_zone
566 if flavor in flavors:
567 self.resources[name]['depends_on'].append(flavor)
568 server_properties["flavor"] = {'get_resource': flavor}
570 server_properties["flavor"] = flavor
573 server_properties['admin_user'] = user
576 self.resources[name]['depends_on'].append(key_name)
577 server_properties['key_name'] = {'get_resource': key_name}
580 self.resources[name]['depends_on'].extend(ports)
582 server_properties['networks'].append(
583 {'port': {'get_resource': port}}
587 for i, _ in enumerate(networks):
588 server_properties['networks'].append({'network': networks[i]})
591 server_properties['scheduler_hints'] = scheduler_hints
594 server_properties['user_data'] = user_data
597 assert isinstance(metadata, collections.Mapping)
598 server_properties['metadata'] = metadata
600 if additional_properties:
601 assert isinstance(additional_properties, collections.Mapping)
602 for prop in additional_properties:
603 server_properties[prop] = additional_properties[prop]
605 server_properties['config_drive'] = True
607 self.resources[name]['properties'] = server_properties
609 self._template['outputs'][name] = {
610 'description': 'VM UUID',
611 'value': {'get_resource': name}
614 def create(self, block=True, timeout=3600):
615 """Creates a stack in the target based on the stored template
617 :param block: (bool) Wait for Heat create to finish
618 :param timeout: (int) Timeout in seconds for Heat create,
620 :return A dict with the requested output values from the template
622 log.info("Creating stack '%s' START", self.name)
624 start_time = time.time()
625 stack = HeatStack(self.name)
626 stack.create(self._template, self.heat_parameters, block, timeout)
629 log.info("Creating stack '%s' DONE in %d secs",
630 self.name, time.time() - start_time)
633 if stack.status != self.HEAT_STATUS_COMPLETE:
634 for event in stack.get_failures():
635 log.error("%s", event.resource_status_reason)
636 log.error(pprint.pformat(self._template))
637 raise exceptions.HeatTemplateError(stack_name=self.name)
639 log.info("Creating stack '%s' DONE in %d secs",
640 self.name, time.time() - start_time)