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
22 from oslo_serialization import jsonutils
23 from oslo_utils import encodeutils
26 import yardstick.common.openstack_utils as op_utils
27 from yardstick.common import exceptions
28 from yardstick.common import template_format
30 log = logging.getLogger(__name__)
33 PROVIDER_SRIOV = "sriov"
38 class HeatStack(object):
39 """Represents a Heat stack (deployed template) """
41 def __init__(self, name):
44 self._cloud = shade.openstack_cloud()
47 def _update_stack_tracking(self):
48 outputs = self._stack.outputs
49 self.outputs = {output['output_key']: output['output_value'] for output
52 _DEPLOYED_STACKS[self.uuid] = self._stack
54 def create(self, template, heat_parameters, wait, timeout):
55 """Creates an OpenStack stack from a template"""
56 with tempfile.NamedTemporaryFile('wb', delete=False) as template_file:
57 template_file.write(jsonutils.dump_as_bytes(template))
59 self._stack = self._cloud.create_stack(
60 self.name, template_file=template_file.name, wait=wait,
61 timeout=timeout, **heat_parameters)
63 self._update_stack_tracking()
66 """Retrieves an existing stack from the target cloud
68 Returns a bool indicating whether the stack exists in the target cloud
69 If the stack exists, it will be stored as self._stack
71 self._stack = self._cloud.get_stack(self.name)
75 self._update_stack_tracking()
80 """Check if any stack has been deployed"""
81 return len(_DEPLOYED_STACKS) > 0
83 def delete(self, wait=True):
84 """Deletes a stack in the target cloud"""
89 ret = self._cloud.delete_stack(self.uuid, wait=wait)
91 # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
92 # tries to retrieve and read the stack status when it's already
96 _DEPLOYED_STACKS.pop(self.uuid)
102 """Delete all deployed stacks"""
103 for stack in _DEPLOYED_STACKS:
108 """Retrieve the current stack status"""
110 return self._stack.status
114 """Retrieve the current stack ID"""
116 return self._stack.id
119 class HeatTemplate(object):
120 """Describes a Heat template and a method to deploy template to a stack"""
122 DESCRIPTION_TEMPLATE = """
123 Stack built by the yardstick framework for %s on host %s %s.
124 All referred generated resources are prefixed with the template
128 HEAT_WAIT_LOOP_INTERVAL = 2
129 HEAT_STATUS_COMPLETE = 'COMPLETE'
131 def _init_template(self):
132 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
134 'heat_template_version': '2013-05-23',
135 'description': self.DESCRIPTION_TEMPLATE % (
137 socket.gethostname(),
145 # short hand for resources part of template
146 self.resources = self._template['resources']
148 def __init__(self, name, template_file=None, heat_parameters=None):
150 self.keystone_client = None
151 self.heat_parameters = {}
153 # heat_parameters is passed to heat in stack create, empty dict when
154 # yardstick creates the template (no get_param in resources part)
156 self.heat_parameters = heat_parameters
159 with open(template_file) as stream:
160 log.info('Parsing external template: %s', template_file)
161 template_str = stream.read()
162 self._template = template_format.parse(template_str)
163 self._parameters = heat_parameters
165 self._init_template()
167 log.debug("template object '%s' created", name)
169 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
170 is_public=True, rxtx_factor=1.0, swap=0,
172 """add to the template a Flavor description"""
175 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
176 "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
177 "swap '%d' extra_specs '%s'",
178 name, vcpus, ram, disk, ephemeral, is_public,
179 rxtx_factor, swap, str(extra_specs))
182 assert isinstance(extra_specs, collections.Mapping)
184 self.resources[name] = {
185 'type': 'OS::Nova::Flavor',
186 'properties': {'name': name,
191 'rxtx_factor': rxtx_factor,
193 'is_public': is_public,
194 'ephemeral': ephemeral,
195 'extra_specs': extra_specs}
198 self._template['outputs'][name] = {
199 'description': 'Flavor %s ID' % name,
200 'value': {'get_resource': name}
203 def add_volume(self, name, size=10):
204 """add to the template a volume description"""
205 log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
207 self.resources[name] = {
208 'type': 'OS::Cinder::Volume',
209 'properties': {'name': name,
213 self._template['outputs'][name] = {
214 'description': 'Volume %s ID' % name,
215 'value': {'get_resource': name}
218 def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
219 """add to the template an association of volume to instance"""
220 log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
223 name = "%s-%s" % (server_name, volume_name)
225 volume_id = op_utils.get_volume_id(volume_name)
227 volume_id = {'get_resource': volume_name}
228 self.resources[name] = {
229 'type': 'OS::Cinder::VolumeAttachment',
230 'properties': {'instance_uuid': {'get_resource': server_name},
231 'volume_id': volume_id}
235 self.resources[name]['properties']['mountpoint'] = mountpoint
237 def add_network(self, name, physical_network='physnet1', provider=None,
238 segmentation_id=None, port_security_enabled=None, network_type=None):
239 """add to the template a Neutron Net"""
240 log.debug("adding Neutron::Net '%s'", name)
242 self.resources[name] = {
243 'type': 'OS::Neutron::Net',
249 self.resources[name] = {
250 'type': 'OS::Neutron::ProviderNet',
253 'network_type': 'flat' if network_type is None else network_type,
254 'physical_network': physical_network,
258 self.resources[name]['properties']['segmentation_id'] = segmentation_id
259 if network_type is None:
260 self.resources[name]['properties']['network_type'] = 'vlan'
261 # if port security is not defined then don't add to template:
262 # some deployments don't have port security plugin installed
263 if port_security_enabled is not None:
264 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
266 def add_server_group(self, name, policies): # pragma: no cover
267 """add to the template a ServerGroup"""
268 log.debug("adding Nova::ServerGroup '%s'", name)
269 policies = policies if isinstance(policies, list) else [policies]
270 self.resources[name] = {
271 'type': 'OS::Nova::ServerGroup',
272 'properties': {'name': name,
273 'policies': policies}
276 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
277 """add to the template a Neutron Subnet
279 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
281 self.resources[name] = {
282 'type': 'OS::Neutron::Subnet',
283 'depends_on': network,
287 'network_id': {'get_resource': network},
288 'enable_dhcp': enable_dhcp,
291 if gateway_ip == 'null':
292 self.resources[name]['properties']['gateway_ip'] = None
293 elif gateway_ip is not None:
294 self.resources[name]['properties']['gateway_ip'] = gateway_ip
296 self._template['outputs'][name] = {
297 'description': 'subnet %s ID' % name,
298 'value': {'get_resource': name}
300 self._template['outputs'][name + "-cidr"] = {
301 'description': 'subnet %s cidr' % name,
302 'value': {'get_attr': [name, 'cidr']}
304 self._template['outputs'][name + "-gateway_ip"] = {
305 'description': 'subnet %s gateway_ip' % name,
306 'value': {'get_attr': [name, 'gateway_ip']}
309 def add_router(self, name, ext_gw_net, subnet_name):
310 """add to the template a Neutron Router and interface"""
311 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
312 self.resources[name] = {
313 'type': 'OS::Neutron::Router',
314 'depends_on': [subnet_name],
317 'external_gateway_info': {
318 'network': ext_gw_net
323 def add_router_interface(self, name, router_name, subnet_name):
324 """add to the template a Neutron RouterInterface and interface"""
325 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
326 "subnet:'%s'", name, router_name, subnet_name)
327 self.resources[name] = {
328 'type': 'OS::Neutron::RouterInterface',
329 'depends_on': [router_name, subnet_name],
331 'router_id': {'get_resource': router_name},
332 'subnet_id': {'get_resource': subnet_name}
336 def add_port(self, name, network_name, subnet_name, vnic_type, sec_group_id=None,
337 provider=None, allowed_address_pairs=None):
338 """add to the template a named Neutron Port
340 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', vnic_type:'%s', "
341 "secgroup:%s", name, network_name, subnet_name, vnic_type, sec_group_id)
342 self.resources[name] = {
343 'type': 'OS::Neutron::Port',
344 'depends_on': [subnet_name],
347 'binding:vnic_type': vnic_type,
348 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
349 'network_id': {'get_resource': network_name},
350 'replacement_policy': 'AUTO',
354 if provider == PROVIDER_SRIOV:
355 self.resources[name]['properties']['binding:vnic_type'] = \
359 self.resources[name]['depends_on'].append(sec_group_id)
360 self.resources[name]['properties']['security_groups'] = \
363 if allowed_address_pairs:
364 self.resources[name]['properties'][
365 'allowed_address_pairs'] = allowed_address_pairs
367 self._template['outputs'][name] = {
368 'description': 'Address for interface %s' % name,
369 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
371 self._template['outputs'][name + "-subnet_id"] = {
372 'description': 'Address for interface %s' % name,
373 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
375 self._template['outputs'][name + "-mac_address"] = {
376 'description': 'MAC Address for interface %s' % name,
377 'value': {'get_attr': [name, 'mac_address']}
379 self._template['outputs'][name + "-device_id"] = {
380 'description': 'Device ID for interface %s' % name,
381 'value': {'get_attr': [name, 'device_id']}
383 self._template['outputs'][name + "-network_id"] = {
384 'description': 'Network ID for interface %s' % name,
385 'value': {'get_attr': [name, 'network_id']}
388 def add_floating_ip(self, name, network_name, port_name, router_if_name,
390 """add to the template a Nova FloatingIP resource
391 see: https://bugs.launchpad.net/heat/+bug/1299259
393 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
394 "rif '%s'", name, network_name, port_name, router_if_name)
396 self.resources[name] = {
397 'type': 'OS::Nova::FloatingIP',
398 'depends_on': [port_name, router_if_name],
405 self.resources[name]["depends_on"].append(secgroup_name)
407 self._template['outputs'][name] = {
408 'description': 'floating ip %s' % name,
409 'value': {'get_attr': [name, 'ip']}
412 def add_floating_ip_association(self, name, floating_ip_name, port_name):
413 """add to the template a Nova FloatingIP Association resource
415 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
416 "floating_ip '%s'", name, port_name, floating_ip_name)
418 self.resources[name] = {
419 'type': 'OS::Neutron::FloatingIPAssociation',
420 'depends_on': [port_name],
422 'floatingip_id': {'get_resource': floating_ip_name},
423 'port_id': {'get_resource': port_name}
427 def add_keypair(self, name, key_id):
428 """add to the template a Nova KeyPair"""
429 log.debug("adding Nova::KeyPair '%s'", name)
430 self.resources[name] = {
431 'type': 'OS::Nova::KeyPair',
434 # resource_string returns bytes, so we must decode to unicode
435 'public_key': encodeutils.safe_decode(
436 pkg_resources.resource_string(
437 'yardstick.resources',
438 'files/yardstick_key-' +
444 def add_servergroup(self, name, policy):
445 """add to the template a Nova ServerGroup"""
446 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
447 if policy not in ["anti-affinity", "affinity"]:
448 raise ValueError(policy)
450 self.resources[name] = {
451 'type': 'OS::Nova::ServerGroup',
458 self._template['outputs'][name] = {
459 'description': 'ID Server Group %s' % name,
460 'value': {'get_resource': name}
463 def add_security_group(self, name):
464 """add to the template a Neutron SecurityGroup"""
465 log.debug("adding Neutron::SecurityGroup '%s'", name)
466 self.resources[name] = {
467 'type': 'OS::Neutron::SecurityGroup',
470 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
472 {'remote_ip_prefix': '0.0.0.0/0',
474 'port_range_min': '1',
475 'port_range_max': '65535'},
476 {'remote_ip_prefix': '0.0.0.0/0',
478 'port_range_min': '1',
479 'port_range_max': '65535'},
480 {'remote_ip_prefix': '0.0.0.0/0',
482 {'remote_ip_prefix': '::/0',
485 'port_range_min': '1',
486 'port_range_max': '65535'},
487 {'remote_ip_prefix': '::/0',
490 'port_range_min': '1',
491 'port_range_max': '65535'},
492 {'remote_ip_prefix': '::/0',
494 'protocol': 'ipv6-icmp'},
495 {'remote_ip_prefix': '0.0.0.0/0',
496 'direction': 'egress',
498 'port_range_min': '1',
499 'port_range_max': '65535'},
500 {'remote_ip_prefix': '0.0.0.0/0',
501 'direction': 'egress',
503 'port_range_min': '1',
504 'port_range_max': '65535'},
505 {'remote_ip_prefix': '0.0.0.0/0',
506 'direction': 'egress',
508 {'remote_ip_prefix': '::/0',
509 'direction': 'egress',
512 'port_range_min': '1',
513 'port_range_max': '65535'},
514 {'remote_ip_prefix': '::/0',
515 'direction': 'egress',
518 'port_range_min': '1',
519 'port_range_max': '65535'},
520 {'remote_ip_prefix': '::/0',
521 'direction': 'egress',
523 'protocol': 'ipv6-icmp'},
528 self._template['outputs'][name] = {
529 'description': 'ID of Security Group',
530 'value': {'get_resource': name}
533 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
534 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
535 additional_properties=None, availability_zone=None):
536 """add to the template a Nova Server """
537 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
538 "ports %s", name, image, flavor, ports)
540 self.resources[name] = {
541 'type': 'OS::Nova::Server',
545 server_properties = {
549 'networks': [] # list of dictionaries
551 if availability_zone:
552 server_properties["availability_zone"] = availability_zone
554 if flavor in flavors:
555 self.resources[name]['depends_on'].append(flavor)
556 server_properties["flavor"] = {'get_resource': flavor}
558 server_properties["flavor"] = flavor
561 server_properties['admin_user'] = user
564 self.resources[name]['depends_on'].append(key_name)
565 server_properties['key_name'] = {'get_resource': key_name}
568 self.resources[name]['depends_on'].extend(ports)
570 server_properties['networks'].append(
571 {'port': {'get_resource': port}}
575 for i, _ in enumerate(networks):
576 server_properties['networks'].append({'network': networks[i]})
579 server_properties['scheduler_hints'] = scheduler_hints
582 server_properties['user_data'] = user_data
585 assert isinstance(metadata, collections.Mapping)
586 server_properties['metadata'] = metadata
588 if additional_properties:
589 assert isinstance(additional_properties, collections.Mapping)
590 for prop in additional_properties:
591 server_properties[prop] = additional_properties[prop]
593 server_properties['config_drive'] = True
595 self.resources[name]['properties'] = server_properties
597 self._template['outputs'][name] = {
598 'description': 'VM UUID',
599 'value': {'get_resource': name}
602 def create(self, block=True, timeout=3600):
603 """Creates a stack in the target based on the stored template
605 :param block: (bool) Wait for Heat create to finish
606 :param timeout: (int) Timeout in seconds for Heat create,
608 :return A dict with the requested output values from the template
610 log.info("Creating stack '%s' START", self.name)
612 start_time = time.time()
613 stack = HeatStack(self.name)
614 stack.create(self._template, self.heat_parameters, block, timeout)
617 log.info("Creating stack '%s' DONE in %d secs",
618 self.name, time.time() - start_time)
621 if stack.status != self.HEAT_STATUS_COMPLETE:
622 raise exceptions.HeatTemplateError(stack_name=self.name)
624 log.info("Creating stack '%s' DONE in %d secs",
625 self.name, time.time() - start_time)