1 ##############################################################################
2 # Copyright (c) 2015 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"""
19 from oslo_utils import encodeutils
23 from yardstick.common import template_format
24 import yardstick.common.openstack_utils as op_utils
27 log = logging.getLogger(__name__)
30 HEAT_KEY_UUID_LENGTH = 8
33 def get_short_key_uuid(uuid):
34 return str(uuid)[:HEAT_KEY_UUID_LENGTH]
37 class HeatObject(object):
38 ''' base class for template and stack'''
40 self._heat_client = None
43 def _get_heat_client(self):
44 '''returns a heat client instance'''
46 if self._heat_client is None:
47 sess = op_utils.get_session()
48 heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
49 self._heat_client = heatclient.client.Client(
50 op_utils.get_heat_api_version(),
51 endpoint=heat_endpoint, session=sess)
53 return self._heat_client
56 '''returns stack state as a string'''
57 heat = self._get_heat_client()
58 stack = heat.stacks.get(self.uuid)
59 return getattr(stack, 'stack_status')
62 class HeatStack(HeatObject):
63 ''' Represents a Heat stack (deployed template) '''
66 def __init__(self, name):
67 super(HeatStack, self).__init__()
71 HeatStack.stacks.append(self)
75 '''check if any stack has been deployed'''
76 return len(HeatStack.stacks) > 0
79 '''deletes a stack from the target cloud using heat'''
83 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
84 heat = self._get_heat_client()
85 template = heat.stacks.get(self.uuid)
86 start_time = time.time()
88 status = self.status()
90 while status != u'DELETE_COMPLETE':
91 log.debug("stack state %s", status)
92 if status == u'DELETE_FAILED':
94 heat.stacks.get(self.uuid).stack_status_reason)
97 status = self.status()
99 end_time = time.time()
100 log.info("Deleted stack '%s' in %d secs", self.name,
101 end_time - start_time)
104 def delete(self, block=True, retries=3):
105 '''deletes a stack in the target cloud using heat (with retry)
106 Sometimes delete fail with "InternalServerError" and the next attempt
107 succeeds. So it is worthwhile to test a couple of times.
109 if self.uuid is None:
121 except RuntimeError as err:
126 # if still not deleted try once more and let it fail everything
127 if self.uuid is not None:
130 HeatStack.stacks.remove(self)
134 for stack in HeatStack.stacks[:]:
139 raise RuntimeError("not implemented")
142 class HeatTemplate(HeatObject):
143 '''Describes a Heat template and a method to deploy template to a stack'''
145 def _init_template(self):
147 self._template['heat_template_version'] = '2013-05-23'
149 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
150 self._template['description'] = \
151 '''Stack built by the yardstick framework for %s on host %s %s.
152 All referred generated resources are prefixed with the template
153 name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
154 timestamp, self.name)
156 # short hand for resources part of template
157 self.resources = self._template['resources'] = {}
159 self._template['outputs'] = {}
161 def __init__(self, name, template_file=None, heat_parameters=None):
162 super(HeatTemplate, self).__init__()
164 self.state = "NOT_CREATED"
165 self.keystone_client = None
166 self.heat_client = None
167 self.heat_parameters = {}
169 # heat_parameters is passed to heat in stack create, empty dict when
170 # yardstick creates the template (no get_param in resources part)
172 self.heat_parameters = heat_parameters
175 with open(template_file) as stream:
176 print "Parsing external template:", template_file
177 template_str = stream.read()
178 self._template = template_format.parse(template_str)
179 self._parameters = heat_parameters
181 self._init_template()
183 # holds results of requested output after deployment
186 log.debug("template object '%s' created", name)
188 def add_network(self, name):
189 '''add to the template a Neutron Net'''
190 log.debug("adding Neutron::Net '%s'", name)
191 self.resources[name] = {
192 'type': 'OS::Neutron::Net',
193 'properties': {'name': name}
196 def add_subnet(self, name, network, cidr):
197 '''add to the template a Neutron Subnet'''
198 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
200 self.resources[name] = {
201 'type': 'OS::Neutron::Subnet',
202 'depends_on': network,
206 'network_id': {'get_resource': network}
210 self._template['outputs'][name] = {
211 'description': 'subnet %s ID' % name,
212 'value': {'get_resource': name}
215 def add_router(self, name, ext_gw_net, subnet_name):
216 '''add to the template a Neutron Router and interface'''
217 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
219 self.resources[name] = {
220 'type': 'OS::Neutron::Router',
221 'depends_on': [subnet_name],
224 'external_gateway_info': {
225 'network': ext_gw_net
230 def add_router_interface(self, name, router_name, subnet_name):
231 '''add to the template a Neutron RouterInterface and interface'''
232 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
233 "subnet:'%s'", name, router_name, subnet_name)
235 self.resources[name] = {
236 'type': 'OS::Neutron::RouterInterface',
237 'depends_on': [router_name, subnet_name],
239 'router_id': {'get_resource': router_name},
240 'subnet_id': {'get_resource': subnet_name}
244 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
245 '''add to the template a named Neutron Port'''
246 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
247 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
248 self.resources[name] = {
249 'type': 'OS::Neutron::Port',
250 'depends_on': [subnet_name],
253 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
254 'network_id': {'get_resource': network_name},
255 'replacement_policy': 'AUTO',
260 self.resources[name]['depends_on'].append(sec_group_id)
261 self.resources[name]['properties']['security_groups'] = \
264 self._template['outputs'][name] = {
265 'description': 'Address for interface %s' % name,
266 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
269 def add_floating_ip(self, name, network_name, port_name, router_if_name,
271 '''add to the template a Nova FloatingIP resource
272 see: https://bugs.launchpad.net/heat/+bug/1299259
274 log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
275 "rif '%s'", name, network_name, port_name, router_if_name)
277 self.resources[name] = {
278 'type': 'OS::Nova::FloatingIP',
279 'depends_on': [port_name, router_if_name],
286 self.resources[name]["depends_on"].append(secgroup_name)
288 self._template['outputs'][name] = {
289 'description': 'floating ip %s' % name,
290 'value': {'get_attr': [name, 'ip']}
293 def add_floating_ip_association(self, name, floating_ip_name, port_name):
294 '''add to the template a Nova FloatingIP Association resource
296 log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
297 "floating_ip '%s'", name, port_name, floating_ip_name)
299 self.resources[name] = {
300 'type': 'OS::Neutron::FloatingIPAssociation',
301 'depends_on': [port_name],
303 'floatingip_id': {'get_resource': floating_ip_name},
304 'port_id': {'get_resource': port_name}
308 def add_keypair(self, name, key_uuid):
309 '''add to the template a Nova KeyPair'''
310 log.debug("adding Nova::KeyPair '%s'", name)
311 self.resources[name] = {
312 'type': 'OS::Nova::KeyPair',
315 'public_key': encodeutils.safe_decode(
316 pkg_resources.resource_string(
317 'yardstick.resources',
318 'files/yardstick_key-' +
319 get_short_key_uuid(key_uuid) + '.pub'),
324 def add_servergroup(self, name, policy):
325 '''add to the template a Nova ServerGroup'''
326 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
327 if policy not in ["anti-affinity", "affinity"]:
328 raise ValueError(policy)
330 self.resources[name] = {
331 'type': 'OS::Nova::ServerGroup',
338 self._template['outputs'][name] = {
339 'description': 'ID Server Group %s' % name,
340 'value': {'get_resource': name}
343 def add_security_group(self, name):
344 '''add to the template a Neutron SecurityGroup'''
345 log.debug("adding Neutron::SecurityGroup '%s'", name)
346 self.resources[name] = {
347 'type': 'OS::Neutron::SecurityGroup',
350 'description': "Group allowing icmp and upd/tcp on all ports",
352 {'remote_ip_prefix': '0.0.0.0/0',
354 'port_range_min': '1',
355 'port_range_max': '65535'},
356 {'remote_ip_prefix': '0.0.0.0/0',
358 'port_range_min': '1',
359 'port_range_max': '65535'},
360 {'remote_ip_prefix': '0.0.0.0/0',
366 self._template['outputs'][name] = {
367 'description': 'ID of Security Group',
368 'value': {'get_resource': name}
371 def add_server(self, name, image, flavor, ports=None, networks=None,
372 scheduler_hints=None, user=None, key_name=None,
373 user_data=None, metadata=None, additional_properties=None):
374 '''add to the template a Nova Server'''
375 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
376 "ports %s", name, image, flavor, ports)
378 self.resources[name] = {
379 'type': 'OS::Nova::Server'
382 server_properties = {
386 'networks': [] # list of dictionaries
390 server_properties['admin_user'] = user
393 self.resources[name]['depends_on'] = [key_name]
394 server_properties['key_name'] = {'get_resource': key_name}
397 self.resources[name]['depends_on'] = ports
400 server_properties['networks'].append(
401 {'port': {'get_resource': port}}
405 for i in range(len(networks)):
406 server_properties['networks'].append({'network': networks[i]})
409 server_properties['scheduler_hints'] = scheduler_hints
412 server_properties['user_data'] = user_data
415 assert type(metadata) is dict
416 server_properties['metadata'] = metadata
418 if additional_properties:
419 assert type(additional_properties) is dict
420 for prop in additional_properties:
421 server_properties[prop] = additional_properties[prop]
423 server_properties['config_drive'] = True
425 self.resources[name]['properties'] = server_properties
427 self._template['outputs'][name] = {
428 'description': 'VM UUID',
429 'value': {'get_resource': name}
432 def create(self, block=True):
433 '''creates a template in the target cloud using heat
434 returns a dict with the requested output values from the template'''
435 log.info("Creating stack '%s'", self.name)
437 # create stack early to support cleanup, e.g. ctrl-c while waiting
438 stack = HeatStack(self.name)
440 heat = self._get_heat_client()
441 json_template = json.dumps(self._template)
442 start_time = time.time()
443 stack.uuid = self.uuid = heat.stacks.create(
444 stack_name=self.name, template=json_template,
445 parameters=self.heat_parameters)['stack']['id']
447 status = self.status()
450 while status != u'CREATE_COMPLETE':
451 log.debug("stack state %s", status)
452 if status == u'CREATE_FAILED':
453 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
454 'stack_status_reason'))
457 status = self.status()
459 end_time = time.time()
460 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
462 for output in outputs:
463 self.outputs[output["output_key"].encode("ascii")] = \
464 output["output_value"].encode("ascii")
466 log.info("Created stack '%s' in %d secs",
467 self.name, end_time - start_time)
469 stack.outputs = self.outputs