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 PROVIDER_SRIOV = "sriov"
39 class HeatStack(object):
40 """Represents a Heat stack (deployed template) """
42 def __init__(self, name):
45 self._cloud = shade.openstack_cloud()
48 def _update_stack_tracking(self):
49 outputs = self._stack.outputs
50 self.outputs = {output['output_key']: output['output_value'] for output
53 _DEPLOYED_STACKS[self.uuid] = self._stack
55 def create(self, template, heat_parameters, wait, timeout):
56 """Creates an OpenStack stack from a template"""
57 with tempfile.NamedTemporaryFile('wb', delete=False) as template_file:
58 template_file.write(jsonutils.dump_as_bytes(template))
60 self._stack = self._cloud.create_stack(
61 self.name, template_file=template_file.name, wait=wait,
62 timeout=timeout, **heat_parameters)
64 self._update_stack_tracking()
67 """Retrieves an existing stack from the target cloud
69 Returns a bool indicating whether the stack exists in the target cloud
70 If the stack exists, it will be stored as self._stack
72 self._stack = self._cloud.get_stack(self.name)
76 self._update_stack_tracking()
81 """Check if any stack has been deployed"""
82 return len(_DEPLOYED_STACKS) > 0
84 def delete(self, wait=True):
85 """Deletes a stack in the target cloud"""
90 ret = self._cloud.delete_stack(self.uuid, wait=wait)
92 # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
93 # tries to retrieve and read the stack status when it's already
97 _DEPLOYED_STACKS.pop(self.uuid)
103 """Delete all deployed stacks"""
104 for stack in _DEPLOYED_STACKS:
109 """Retrieve the current stack status"""
111 return self._stack.status
115 """Retrieve the current stack ID"""
117 return self._stack.id
120 class HeatTemplate(object):
121 """Describes a Heat template and a method to deploy template to a stack"""
123 DESCRIPTION_TEMPLATE = """
124 Stack built by the yardstick framework for %s on host %s %s.
125 All referred generated resources are prefixed with the template
129 HEAT_WAIT_LOOP_INTERVAL = 2
130 HEAT_STATUS_COMPLETE = 'COMPLETE'
132 def _init_template(self):
133 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
135 'heat_template_version': '2013-05-23',
136 'description': self.DESCRIPTION_TEMPLATE % (
138 socket.gethostname(),
146 # short hand for resources part of template
147 self.resources = self._template['resources']
149 def __init__(self, name, template_file=None, heat_parameters=None):
151 self.keystone_client = None
152 self.heat_parameters = {}
154 # heat_parameters is passed to heat in stack create, empty dict when
155 # yardstick creates the template (no get_param in resources part)
157 self.heat_parameters = heat_parameters
160 with open(template_file) as stream:
161 log.info('Parsing external template: %s', template_file)
162 template_str = stream.read()
163 self._template = template_format.parse(template_str)
164 self._parameters = heat_parameters
166 self._init_template()
168 log.debug("template object '%s' created", name)
170 def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
171 is_public=True, rxtx_factor=1.0, swap=0,
173 """add to the template a Flavor description"""
176 log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
177 "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
178 "swap '%d' extra_specs '%s'",
179 name, vcpus, ram, disk, ephemeral, is_public,
180 rxtx_factor, swap, str(extra_specs))
183 assert isinstance(extra_specs, collections.Mapping)
185 self.resources[name] = {
186 'type': 'OS::Nova::Flavor',
187 'properties': {'name': name,
192 'rxtx_factor': rxtx_factor,
194 'is_public': is_public,
195 'ephemeral': ephemeral,
196 'extra_specs': extra_specs}
199 self._template['outputs'][name] = {
200 'description': 'Flavor %s ID' % name,
201 'value': {'get_resource': name}
204 def add_volume(self, name, size=10):
205 """add to the template a volume description"""
206 log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
208 self.resources[name] = {
209 'type': 'OS::Cinder::Volume',
210 'properties': {'name': name,
214 self._template['outputs'][name] = {
215 'description': 'Volume %s ID' % name,
216 'value': {'get_resource': name}
219 def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
220 """add to the template an association of volume to instance"""
221 log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
224 name = "%s-%s" % (server_name, volume_name)
226 volume_id = op_utils.get_volume_id(volume_name)
228 volume_id = {'get_resource': volume_name}
229 self.resources[name] = {
230 'type': 'OS::Cinder::VolumeAttachment',
231 'properties': {'instance_uuid': {'get_resource': server_name},
232 'volume_id': volume_id}
236 self.resources[name]['properties']['mountpoint'] = mountpoint
238 def add_network(self, name, physical_network='physnet1', provider=None,
239 segmentation_id=None, port_security_enabled=None, network_type=None):
240 """add to the template a Neutron Net"""
241 log.debug("adding Neutron::Net '%s'", name)
243 self.resources[name] = {
244 'type': 'OS::Neutron::Net',
250 self.resources[name] = {
251 'type': 'OS::Neutron::ProviderNet',
254 'network_type': 'flat' if network_type is None else network_type,
255 'physical_network': physical_network,
259 self.resources[name]['properties']['segmentation_id'] = segmentation_id
260 if network_type is None:
261 self.resources[name]['properties']['network_type'] = 'vlan'
262 # if port security is not defined then don't add to template:
263 # some deployments don't have port security plugin installed
264 if port_security_enabled is not None:
265 self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
267 def add_server_group(self, name, policies): # pragma: no cover
268 """add to the template a ServerGroup"""
269 log.debug("adding Nova::ServerGroup '%s'", name)
270 policies = policies if isinstance(policies, list) else [policies]
271 self.resources[name] = {
272 'type': 'OS::Nova::ServerGroup',
273 'properties': {'name': name,
274 'policies': policies}
277 def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
278 """add to the template a Neutron Subnet
280 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
282 self.resources[name] = {
283 'type': 'OS::Neutron::Subnet',
284 'depends_on': network,
288 'network_id': {'get_resource': network},
289 'enable_dhcp': enable_dhcp,
292 if gateway_ip == 'null':
293 self.resources[name]['properties']['gateway_ip'] = None
294 elif gateway_ip is not None:
295 self.resources[name]['properties']['gateway_ip'] = gateway_ip
297 self._template['outputs'][name] = {
298 'description': 'subnet %s ID' % name,
299 'value': {'get_resource': name}
301 self._template['outputs'][name + "-cidr"] = {
302 'description': 'subnet %s cidr' % name,
303 'value': {'get_attr': [name, 'cidr']}
305 self._template['outputs'][name + "-gateway_ip"] = {
306 'description': 'subnet %s gateway_ip' % name,
307 'value': {'get_attr': [name, 'gateway_ip']}
310 def add_router(self, name, ext_gw_net, subnet_name):
311 """add to the template a Neutron Router and interface"""
312 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
313 self.resources[name] = {
314 'type': 'OS::Neutron::Router',
315 'depends_on': [subnet_name],
318 'external_gateway_info': {
319 'network': ext_gw_net
324 def add_router_interface(self, name, router_name, subnet_name):
325 """add to the template a Neutron RouterInterface and interface"""
326 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
327 "subnet:'%s'", name, router_name, subnet_name)
328 self.resources[name] = {
329 'type': 'OS::Neutron::RouterInterface',
330 'depends_on': [router_name, subnet_name],
332 'router_id': {'get_resource': router_name},
333 'subnet_id': {'get_resource': subnet_name}
337 def add_port(self, name, network, sec_group_id=None,
338 provider=None, allowed_address_pairs=None):
339 """add to the template a named Neutron Port
341 net_is_existing = network.net_flags.get(consts.IS_EXISTING)
342 depends_on = [] if net_is_existing else [network.subnet_stack_name]
343 fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
344 {'subnet': {'get_resource': network.subnet_stack_name}}]
345 network_ = network.name if net_is_existing else {
346 'get_resource': network.stack_name}
347 self.resources[name] = {
348 'type': 'OS::Neutron::Port',
349 'depends_on': depends_on,
352 'binding:vnic_type': network.vnic_type,
353 'fixed_ips': fixed_ips,
358 if provider == PROVIDER_SRIOV:
359 self.resources[name]['properties']['binding:vnic_type'] = \
363 self.resources[name]['depends_on'].append(sec_group_id)
364 self.resources[name]['properties']['security_groups'] = \
367 if allowed_address_pairs:
368 self.resources[name]['properties'][
369 'allowed_address_pairs'] = allowed_address_pairs
371 log.debug("adding Neutron::Port %s", self.resources[name])
373 self._template['outputs'][name] = {
374 'description': 'Address for interface %s' % name,
375 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
377 self._template['outputs'][name + "-subnet_id"] = {
378 'description': 'Address for interface %s' % name,
379 'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
381 self._template['outputs'][name + "-mac_address"] = {
382 'description': 'MAC Address for interface %s' % name,
383 'value': {'get_attr': [name, 'mac_address']}
385 self._template['outputs'][name + "-device_id"] = {
386 'description': 'Device ID for interface %s' % name,
387 'value': {'get_attr': [name, 'device_id']}
389 self._template['outputs'][name + "-network_id"] = {
390 'description': 'Network ID for interface %s' % name,
391 'value': {'get_attr': [name, 'network_id']}
394 def add_floating_ip(self, name, network_name, port_name, router_if_name,
396 """add to the template a Nova FloatingIP resource
397 see: https://bugs.launchpad.net/heat/+bug/1299259
399 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
400 "rif '%s'", name, network_name, port_name, router_if_name)
402 self.resources[name] = {
403 'type': 'OS::Nova::FloatingIP',
404 'depends_on': [port_name, router_if_name],
411 self.resources[name]["depends_on"].append(secgroup_name)
413 self._template['outputs'][name] = {
414 'description': 'floating ip %s' % name,
415 'value': {'get_attr': [name, 'ip']}
418 def add_floating_ip_association(self, name, floating_ip_name, port_name):
419 """add to the template a Nova FloatingIP Association resource
421 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
422 "floating_ip '%s'", name, port_name, floating_ip_name)
424 self.resources[name] = {
425 'type': 'OS::Neutron::FloatingIPAssociation',
426 'depends_on': [port_name],
428 'floatingip_id': {'get_resource': floating_ip_name},
429 'port_id': {'get_resource': port_name}
433 def add_keypair(self, name, key_id):
434 """add to the template a Nova KeyPair"""
435 log.debug("adding Nova::KeyPair '%s'", name)
436 self.resources[name] = {
437 'type': 'OS::Nova::KeyPair',
440 # resource_string returns bytes, so we must decode to unicode
441 'public_key': encodeutils.safe_decode(
442 pkg_resources.resource_string(
443 'yardstick.resources',
444 'files/yardstick_key-' +
450 def add_servergroup(self, name, policy):
451 """add to the template a Nova ServerGroup"""
452 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
453 if policy not in ["anti-affinity", "affinity"]:
454 raise ValueError(policy)
456 self.resources[name] = {
457 'type': 'OS::Nova::ServerGroup',
464 self._template['outputs'][name] = {
465 'description': 'ID Server Group %s' % name,
466 'value': {'get_resource': name}
469 def add_security_group(self, name):
470 """add to the template a Neutron SecurityGroup"""
471 log.debug("adding Neutron::SecurityGroup '%s'", name)
472 self.resources[name] = {
473 'type': 'OS::Neutron::SecurityGroup',
476 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
478 {'remote_ip_prefix': '0.0.0.0/0',
480 'port_range_min': '1',
481 'port_range_max': '65535'},
482 {'remote_ip_prefix': '0.0.0.0/0',
484 'port_range_min': '1',
485 'port_range_max': '65535'},
486 {'remote_ip_prefix': '0.0.0.0/0',
488 {'remote_ip_prefix': '::/0',
491 'port_range_min': '1',
492 'port_range_max': '65535'},
493 {'remote_ip_prefix': '::/0',
496 'port_range_min': '1',
497 'port_range_max': '65535'},
498 {'remote_ip_prefix': '::/0',
500 'protocol': 'ipv6-icmp'},
501 {'remote_ip_prefix': '0.0.0.0/0',
502 'direction': 'egress',
504 'port_range_min': '1',
505 'port_range_max': '65535'},
506 {'remote_ip_prefix': '0.0.0.0/0',
507 'direction': 'egress',
509 'port_range_min': '1',
510 'port_range_max': '65535'},
511 {'remote_ip_prefix': '0.0.0.0/0',
512 'direction': 'egress',
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',
524 'port_range_min': '1',
525 'port_range_max': '65535'},
526 {'remote_ip_prefix': '::/0',
527 'direction': 'egress',
529 'protocol': 'ipv6-icmp'},
534 self._template['outputs'][name] = {
535 'description': 'ID of Security Group',
536 'value': {'get_resource': name}
539 def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
540 scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
541 additional_properties=None, availability_zone=None):
542 """add to the template a Nova Server """
543 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
544 "ports %s", name, image, flavor, ports)
546 self.resources[name] = {
547 'type': 'OS::Nova::Server',
551 server_properties = {
555 'networks': [] # list of dictionaries
557 if availability_zone:
558 server_properties["availability_zone"] = availability_zone
560 if flavor in flavors:
561 self.resources[name]['depends_on'].append(flavor)
562 server_properties["flavor"] = {'get_resource': flavor}
564 server_properties["flavor"] = flavor
567 server_properties['admin_user'] = user
570 self.resources[name]['depends_on'].append(key_name)
571 server_properties['key_name'] = {'get_resource': key_name}
574 self.resources[name]['depends_on'].extend(ports)
576 server_properties['networks'].append(
577 {'port': {'get_resource': port}}
581 for i, _ in enumerate(networks):
582 server_properties['networks'].append({'network': networks[i]})
585 server_properties['scheduler_hints'] = scheduler_hints
588 server_properties['user_data'] = user_data
591 assert isinstance(metadata, collections.Mapping)
592 server_properties['metadata'] = metadata
594 if additional_properties:
595 assert isinstance(additional_properties, collections.Mapping)
596 for prop in additional_properties:
597 server_properties[prop] = additional_properties[prop]
599 server_properties['config_drive'] = True
601 self.resources[name]['properties'] = server_properties
603 self._template['outputs'][name] = {
604 'description': 'VM UUID',
605 'value': {'get_resource': name}
608 def create(self, block=True, timeout=3600):
609 """Creates a stack in the target based on the stored template
611 :param block: (bool) Wait for Heat create to finish
612 :param timeout: (int) Timeout in seconds for Heat create,
614 :return A dict with the requested output values from the template
616 log.info("Creating stack '%s' START", self.name)
618 start_time = time.time()
619 stack = HeatStack(self.name)
620 stack.create(self._template, self.heat_parameters, block, timeout)
623 log.info("Creating stack '%s' DONE in %d secs",
624 self.name, time.time() - start_time)
627 if stack.status != self.HEAT_STATUS_COMPLETE:
628 raise exceptions.HeatTemplateError(stack_name=self.name)
630 log.info("Creating stack '%s' DONE in %d secs",
631 self.name, time.time() - start_time)