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
29 from yardstick.common import constants as consts
31 log = logging.getLogger(__name__)
34 HEAT_KEY_UUID_LENGTH = 8
36 PROVIDER_SRIOV = "sriov"
41 def get_short_key_uuid(uuid):
42 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
45 class HeatStack(object):
46 """Represents a Heat stack (deployed template) """
48 def __init__(self, name):
51 self._cloud = shade.openstack_cloud()
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)
62 outputs = self._stack.outputs
63 self.outputs = {output['output_key']: output['output_value'] for output
66 _DEPLOYED_STACKS[self.uuid] = self._stack
70 """Check if any stack has been deployed"""
71 return len(_DEPLOYED_STACKS) > 0
73 def delete(self, wait=True):
74 """Deletes a stack in the target cloud"""
79 ret = self._cloud.delete_stack(self.uuid, wait=wait)
81 # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
82 # tries to retrieve and read the stack status when it's already
86 _DEPLOYED_STACKS.pop(self.uuid)
92 """Delete all deployed stacks"""
93 for stack in _DEPLOYED_STACKS:
98 """Retrieve the current stack status"""
100 return self._stack.status
104 """Retrieve the current stack ID"""
106 return self._stack.id
109 class HeatTemplate(object):
110 """Describes a Heat template and a method to deploy template to a stack"""
112 DESCRIPTION_TEMPLATE = """
113 Stack built by the yardstick framework for %s on host %s %s.
114 All referred generated resources are prefixed with the template
118 HEAT_WAIT_LOOP_INTERVAL = 2
119 HEAT_STATUS_COMPLETE = 'COMPLETE'
121 def _init_template(self):
122 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
124 'heat_template_version': '2013-05-23',
125 'description': self.DESCRIPTION_TEMPLATE % (
127 socket.gethostname(),
135 # short hand for resources part of template
136 self.resources = self._template['resources']
138 def __init__(self, name, template_file=None, heat_parameters=None):
140 self.keystone_client = None
141 self.heat_parameters = {}
143 # heat_parameters is passed to heat in stack create, empty dict when
144 # yardstick creates the template (no get_param in resources part)
146 self.heat_parameters = heat_parameters
149 with open(template_file) as stream:
150 log.info('Parsing external template: %s', template_file)
151 template_str = stream.read()
152 self._template = template_format.parse(template_str)
153 self._parameters = heat_parameters
155 self._init_template()
157 log.debug("template object '%s' created", name)
159 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
160 is_public=True, rxtx_factor=1.0, swap=0,
162 """add to the template a Flavor description"""
165 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
166 "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
167 "swap '%d' extra_specs '%s'",
168 name, vcpus, ram, disk, ephemeral, is_public,
169 rxtx_factor, swap, str(extra_specs))
172 assert isinstance(extra_specs, collections.Mapping)
174 self.resources[name] = {
175 'type': 'OS::Nova::Flavor',
176 'properties': {'name': name,
181 'rxtx_factor': rxtx_factor,
183 'is_public': is_public,
184 'ephemeral': ephemeral,
185 'extra_specs': extra_specs}
188 self._template['outputs'][name] = {
189 'description': 'Flavor %s ID' % name,
190 'value': {'get_resource': name}
193 def add_volume(self, name, size=10):
194 """add to the template a volume description"""
195 log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
197 self.resources[name] = {
198 'type': 'OS::Cinder::Volume',
199 'properties': {'name': name,
203 self._template['outputs'][name] = {
204 'description': 'Volume %s ID' % name,
205 'value': {'get_resource': name}
208 def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
209 """add to the template an association of volume to instance"""
210 log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
213 name = "%s-%s" % (server_name, volume_name)
215 volume_id = op_utils.get_volume_id(volume_name)
217 volume_id = {'get_resource': volume_name}
218 self.resources[name] = {
219 'type': 'OS::Cinder::VolumeAttachment',
220 'properties': {'instance_uuid': {'get_resource': server_name},
221 'volume_id': volume_id}
225 self.resources[name]['properties']['mountpoint'] = mountpoint
227 def add_network(self, name, physical_network='physnet1', provider=None,
228 segmentation_id=None, port_security_enabled=None, network_type=None):
229 """add to the template a Neutron Net"""
230 log.debug("adding Neutron::Net '%s'", name)
232 self.resources[name] = {
233 'type': 'OS::Neutron::Net',
239 self.resources[name] = {
240 'type': 'OS::Neutron::ProviderNet',
243 'network_type': 'flat' if network_type is None else network_type,
244 'physical_network': physical_network,
248 self.resources[name]['properties']['segmentation_id'] = segmentation_id
249 if network_type is None:
250 self.resources[name]['properties']['network_type'] = 'vlan'
251 # if port security is not defined then don't add to template:
252 # some deployments don't have port security plugin installed
253 if port_security_enabled is not None:
254 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
256 def add_server_group(self, name, policies): # pragma: no cover
257 """add to the template a ServerGroup"""
258 log.debug("adding Nova::ServerGroup '%s'", name)
259 policies = policies if isinstance(policies, list) else [policies]
260 self.resources[name] = {
261 'type': 'OS::Nova::ServerGroup',
262 'properties': {'name': name,
263 'policies': policies}
266 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
267 """add to the template a Neutron Subnet
269 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
271 self.resources[name] = {
272 'type': 'OS::Neutron::Subnet',
273 'depends_on': network,
277 'network_id': {'get_resource': network},
278 'enable_dhcp': enable_dhcp,
281 if gateway_ip == 'null':
282 self.resources[name]['properties']['gateway_ip'] = None
283 elif gateway_ip is not None:
284 self.resources[name]['properties']['gateway_ip'] = gateway_ip
286 self._template['outputs'][name] = {
287 'description': 'subnet %s ID' % name,
288 'value': {'get_resource': name}
290 self._template['outputs'][name + "-cidr"] = {
291 'description': 'subnet %s cidr' % name,
292 'value': {'get_attr': [name, 'cidr']}
294 self._template['outputs'][name + "-gateway_ip"] = {
295 'description': 'subnet %s gateway_ip' % name,
296 'value': {'get_attr': [name, 'gateway_ip']}
299 def add_router(self, name, ext_gw_net, subnet_name):
300 """add to the template a Neutron Router and interface"""
301 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
302 self.resources[name] = {
303 'type': 'OS::Neutron::Router',
304 'depends_on': [subnet_name],
307 'external_gateway_info': {
308 'network': ext_gw_net
313 def add_router_interface(self, name, router_name, subnet_name):
314 """add to the template a Neutron RouterInterface and interface"""
315 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
316 "subnet:'%s'", name, router_name, subnet_name)
317 self.resources[name] = {
318 'type': 'OS::Neutron::RouterInterface',
319 'depends_on': [router_name, subnet_name],
321 'router_id': {'get_resource': router_name},
322 'subnet_id': {'get_resource': subnet_name}
326 def add_port(self, name, network, sec_group_id=None,
327 provider=None, allowed_address_pairs=None):
328 """add to the template a named Neutron Port
330 net_is_existing = network.net_flags.get(consts.IS_EXISTING)
331 depends_on = [] if net_is_existing else [network.subnet_stack_name]
332 fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
333 {'subnet': {'get_resource': network.subnet_stack_name}}]
334 network_ = network.name if net_is_existing else {
335 'get_resource': network.stack_name}
336 self.resources[name] = {
337 'type': 'OS::Neutron::Port',
338 'depends_on': depends_on,
341 'binding:vnic_type': network.vnic_type,
342 'fixed_ips': fixed_ips,
347 if provider == PROVIDER_SRIOV:
348 self.resources[name]['properties']['binding:vnic_type'] = \
352 self.resources[name]['depends_on'].append(sec_group_id)
353 self.resources[name]['properties']['security_groups'] = \
356 if allowed_address_pairs:
357 self.resources[name]['properties'][
358 'allowed_address_pairs'] = allowed_address_pairs
360 log.debug("adding Neutron::Port %s", self.resources[name])
362 self._template['outputs'][name] = {
363 'description': 'Address for interface %s' % name,
364 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
366 self._template['outputs'][name + "-subnet_id"] = {
367 'description': 'Address for interface %s' % name,
368 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
370 self._template['outputs'][name + "-mac_address"] = {
371 'description': 'MAC Address for interface %s' % name,
372 'value': {'get_attr': [name, 'mac_address']}
374 self._template['outputs'][name + "-device_id"] = {
375 'description': 'Device ID for interface %s' % name,
376 'value': {'get_attr': [name, 'device_id']}
378 self._template['outputs'][name + "-network_id"] = {
379 'description': 'Network ID for interface %s' % name,
380 'value': {'get_attr': [name, 'network_id']}
383 def add_floating_ip(self, name, network_name, port_name, router_if_name,
385 """add to the template a Nova FloatingIP resource
386 see: https://bugs.launchpad.net/heat/+bug/1299259
388 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
389 "rif '%s'", name, network_name, port_name, router_if_name)
391 self.resources[name] = {
392 'type': 'OS::Nova::FloatingIP',
393 'depends_on': [port_name, router_if_name],
400 self.resources[name]["depends_on"].append(secgroup_name)
402 self._template['outputs'][name] = {
403 'description': 'floating ip %s' % name,
404 'value': {'get_attr': [name, 'ip']}
407 def add_floating_ip_association(self, name, floating_ip_name, port_name):
408 """add to the template a Nova FloatingIP Association resource
410 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
411 "floating_ip '%s'", name, port_name, floating_ip_name)
413 self.resources[name] = {
414 'type': 'OS::Neutron::FloatingIPAssociation',
415 'depends_on': [port_name],
417 'floatingip_id': {'get_resource': floating_ip_name},
418 'port_id': {'get_resource': port_name}
422 def add_keypair(self, name, key_uuid):
423 """add to the template a Nova KeyPair"""
424 log.debug("adding Nova::KeyPair '%s'", name)
425 self.resources[name] = {
426 'type': 'OS::Nova::KeyPair',
429 # resource_string returns bytes, so we must decode to unicode
430 'public_key': encodeutils.safe_decode(
431 pkg_resources.resource_string(
432 'yardstick.resources',
433 'files/yardstick_key-' +
434 get_short_key_uuid(key_uuid) + '.pub'),
439 def add_servergroup(self, name, policy):
440 """add to the template a Nova ServerGroup"""
441 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
442 if policy not in ["anti-affinity", "affinity"]:
443 raise ValueError(policy)
445 self.resources[name] = {
446 'type': 'OS::Nova::ServerGroup',
453 self._template['outputs'][name] = {
454 'description': 'ID Server Group %s' % name,
455 'value': {'get_resource': name}
458 def add_security_group(self, name):
459 """add to the template a Neutron SecurityGroup"""
460 log.debug("adding Neutron::SecurityGroup '%s'", name)
461 self.resources[name] = {
462 'type': 'OS::Neutron::SecurityGroup',
465 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
467 {'remote_ip_prefix': '0.0.0.0/0',
469 'port_range_min': '1',
470 'port_range_max': '65535'},
471 {'remote_ip_prefix': '0.0.0.0/0',
473 'port_range_min': '1',
474 'port_range_max': '65535'},
475 {'remote_ip_prefix': '0.0.0.0/0',
477 {'remote_ip_prefix': '::/0',
480 'port_range_min': '1',
481 'port_range_max': '65535'},
482 {'remote_ip_prefix': '::/0',
485 'port_range_min': '1',
486 'port_range_max': '65535'},
487 {'remote_ip_prefix': '::/0',
489 'protocol': 'ipv6-icmp'}
494 self._template['outputs'][name] = {
495 'description': 'ID of Security Group',
496 'value': {'get_resource': name}
499 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
500 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
501 additional_properties=None, availability_zone=None):
502 """add to the template a Nova Server """
503 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
504 "ports %s", name, image, flavor, ports)
506 self.resources[name] = {
507 'type': 'OS::Nova::Server',
511 server_properties = {
515 'networks': [] # list of dictionaries
517 if availability_zone:
518 server_properties["availability_zone"] = availability_zone
520 if flavor in flavors:
521 self.resources[name]['depends_on'].append(flavor)
522 server_properties["flavor"] = {'get_resource': flavor}
524 server_properties["flavor"] = flavor
527 server_properties['admin_user'] = user
530 self.resources[name]['depends_on'].append(key_name)
531 server_properties['key_name'] = {'get_resource': key_name}
534 self.resources[name]['depends_on'].extend(ports)
536 server_properties['networks'].append(
537 {'port': {'get_resource': port}}
541 for i, _ in enumerate(networks):
542 server_properties['networks'].append({'network': networks[i]})
545 server_properties['scheduler_hints'] = scheduler_hints
548 server_properties['user_data'] = user_data
551 assert isinstance(metadata, collections.Mapping)
552 server_properties['metadata'] = metadata
554 if additional_properties:
555 assert isinstance(additional_properties, collections.Mapping)
556 for prop in additional_properties:
557 server_properties[prop] = additional_properties[prop]
559 server_properties['config_drive'] = True
561 self.resources[name]['properties'] = server_properties
563 self._template['outputs'][name] = {
564 'description': 'VM UUID',
565 'value': {'get_resource': name}
568 def create(self, block=True, timeout=3600):
569 """Creates a stack in the target based on the stored template
571 :param block: (bool) Wait for Heat create to finish
572 :param timeout: (int) Timeout in seconds for Heat create,
574 :return A dict with the requested output values from the template
576 log.info("Creating stack '%s' START", self.name)
578 start_time = time.time()
579 stack = HeatStack(self.name)
580 stack.create(self._template, self.heat_parameters, block, timeout)
583 log.info("Creating stack '%s' DONE in %d secs",
584 self.name, time.time() - start_time)
587 if stack.status != self.HEAT_STATUS_COMPLETE:
588 raise exceptions.HeatTemplateError(stack_name=self.name)
590 log.info("Creating stack '%s' DONE in %d secs",
591 self.name, time.time() - start_time)