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
21 import heatclient.client
24 from yardstick.common import template_format
27 log = logging.getLogger(__name__)
30 class HeatObject(object):
31 ''' base class for template and stack'''
33 self._keystone_client = None
34 self._heat_client = None
37 def _get_keystone_client(self):
38 '''returns a keystone client instance'''
40 if self._keystone_client is None:
41 self._keystone_client = keystoneclient.v2_0.client.Client(
42 auth_url=os.environ.get('OS_AUTH_URL'),
43 username=os.environ.get('OS_USERNAME'),
44 password=os.environ.get('OS_PASSWORD'),
45 tenant_name=os.environ.get('OS_TENANT_NAME'))
47 return self._keystone_client
49 def _get_heat_client(self):
50 '''returns a heat client instance'''
52 if self._heat_client is None:
53 keystone = self._get_keystone_client()
54 heat_endpoint = keystone.service_catalog.url_for(
55 service_type='orchestration')
56 self._heat_client = heatclient.client.Client(
57 '1', endpoint=heat_endpoint, token=keystone.auth_token)
59 return self._heat_client
62 '''returns stack state as a string'''
63 heat = self._get_heat_client()
64 stack = heat.stacks.get(self.uuid)
65 return getattr(stack, 'stack_status')
68 class HeatStack(HeatObject):
69 ''' Represents a Heat stack (deployed template) '''
72 def __init__(self, name):
73 super(HeatStack, self).__init__()
77 HeatStack.stacks.append(self)
81 '''check if any stack has been deployed'''
82 return len(HeatStack.stacks) > 0
85 '''deletes a stack from the target cloud using heat'''
89 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
90 heat = self._get_heat_client()
91 template = heat.stacks.get(self.uuid)
92 start_time = time.time()
94 status = self.status()
96 while status != u'DELETE_COMPLETE':
97 log.debug("stack state %s", status)
98 if status == u'DELETE_FAILED':
100 heat.stacks.get(self.uuid).stack_status_reason)
103 status = self.status()
105 end_time = time.time()
106 log.info("Deleted stack '%s' in %d secs", self.name,
107 end_time - start_time)
110 def delete(self, block=True, retries=3):
111 '''deletes a stack in the target cloud using heat (with retry)
112 Sometimes delete fail with "InternalServerError" and the next attempt
113 succeeds. So it is worthwhile to test a couple of times.
115 if self.uuid is None:
127 except RuntimeError as err:
132 # if still not deleted try once more and let it fail everything
133 if self.uuid is not None:
136 HeatStack.stacks.remove(self)
140 for stack in HeatStack.stacks[:]:
145 raise RuntimeError("not implemented")
148 class HeatTemplate(HeatObject):
149 '''Describes a Heat template and a method to deploy template to a stack'''
151 def _init_template(self):
153 self._template['heat_template_version'] = '2013-05-23'
155 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
156 self._template['description'] = \
157 '''Stack built by the yardstick framework for %s on host %s %s.
158 All referred generated resources are prefixed with the template
159 name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
160 timestamp, self.name)
162 # short hand for resources part of template
163 self.resources = self._template['resources'] = {}
165 self._template['outputs'] = {}
167 def __init__(self, name, template_file=None, heat_parameters=None):
168 super(HeatTemplate, self).__init__()
170 self.state = "NOT_CREATED"
171 self.keystone_client = None
172 self.heat_client = None
173 self.heat_parameters = {}
175 # heat_parameters is passed to heat in stack create, empty dict when
176 # yardstick creates the template (no get_param in resources part)
178 self.heat_parameters = heat_parameters
181 with open(template_file) as stream:
182 print "Parsing external template:", template_file
183 template_str = stream.read()
184 self._template = template_format.parse(template_str)
185 self._parameters = heat_parameters
187 self._init_template()
189 # holds results of requested output after deployment
192 log.debug("template object '%s' created", name)
194 def add_network(self, name):
195 '''add to the template a Neutron Net'''
196 log.debug("adding Neutron::Net '%s'", name)
197 self.resources[name] = {
198 'type': 'OS::Neutron::Net',
199 'properties': {'name': name}
202 def add_subnet(self, name, network, cidr):
203 '''add to the template a Neutron Subnet'''
204 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
206 self.resources[name] = {
207 'type': 'OS::Neutron::Subnet',
208 'depends_on': network,
212 'network_id': {'get_resource': network}
216 self._template['outputs'][name] = {
217 'description': 'subnet %s ID' % name,
218 'value': {'get_resource': name}
221 def add_router(self, name, ext_gw_net, subnet_name):
222 '''add to the template a Neutron Router and interface'''
223 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
225 self.resources[name] = {
226 'type': 'OS::Neutron::Router',
227 'depends_on': [subnet_name],
230 'external_gateway_info': {
231 'network': ext_gw_net
236 def add_router_interface(self, name, router_name, subnet_name):
237 '''add to the template a Neutron RouterInterface and interface'''
238 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
239 "subnet:'%s'", name, router_name, subnet_name)
241 self.resources[name] = {
242 'type': 'OS::Neutron::RouterInterface',
243 'depends_on': [router_name, subnet_name],
245 'router_id': {'get_resource': router_name},
246 'subnet_id': {'get_resource': subnet_name}
250 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
251 '''add to the template a named Neutron Port'''
252 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
253 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
254 self.resources[name] = {
255 'type': 'OS::Neutron::Port',
256 'depends_on': [subnet_name],
259 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
260 'network': network_name,
261 'replacement_policy': 'AUTO',
266 self.resources[name]['depends_on'].append(sec_group_id)
267 self.resources[name]['properties']['security_groups'] = \
270 self._template['outputs'][name] = {
271 'description': 'Address for interface %s' % name,
272 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
275 def add_floating_ip(self, name, network_name, port_name, router_if_name,
277 '''add to the template a Neutron FloatingIP resource
278 see: https://bugs.launchpad.net/heat/+bug/1299259
280 log.debug("adding Neutron::FloatingIP '%s', network '%s', port '%s', "
281 "rif '%s'", name, network_name, port_name, router_if_name)
283 self.resources[name] = {
284 'type': 'OS::Neutron::FloatingIP',
285 'depends_on': [port_name, router_if_name],
287 'floating_network': network_name,
288 'port_id': {'get_resource': port_name}
293 self.resources[name]["depends_on"].append(secgroup_name)
295 self._template['outputs'][name] = {
296 'description': 'floating ip %s' % name,
297 'value': {'get_attr': [name, 'floating_ip_address']}
300 def add_keypair(self, name):
301 '''add to the template a Nova KeyPair'''
302 log.debug("adding Nova::KeyPair '%s'", name)
303 self.resources[name] = {
304 'type': 'OS::Nova::KeyPair',
307 'public_key': pkg_resources.resource_string(
308 'yardstick.resources', 'files/yardstick_key.pub')
312 def add_servergroup(self, name, policy):
313 '''add to the template a Nova ServerGroup'''
314 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
315 if policy not in ["anti-affinity", "affinity"]:
316 raise ValueError(policy)
318 self.resources[name] = {
319 'type': 'OS::Nova::ServerGroup',
326 self._template['outputs'][name] = {
327 'description': 'ID Server Group %s' % name,
328 'value': {'get_resource': name}
331 def add_security_group(self, name):
332 '''add to the template a Neutron SecurityGroup'''
333 log.debug("adding Neutron::SecurityGroup '%s'", name)
334 self.resources[name] = {
335 'type': 'OS::Neutron::SecurityGroup',
338 'description': "Group allowing icmp and upd/tcp on all ports",
340 {'remote_ip_prefix': '0.0.0.0/0',
342 {'remote_ip_prefix': '0.0.0.0/0',
344 {'remote_ip_prefix': '0.0.0.0/0',
350 self._template['outputs'][name] = {
351 'description': 'ID of Security Group',
352 'value': {'get_resource': name}
355 def add_server(self, name, image, flavor, ports=None, networks=None,
356 scheduler_hints=None, key_name=None, user_data=None,
357 metadata=None, additional_properties=None):
358 '''add to the template a Nova Server'''
359 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
360 "ports %s", name, image, flavor, ports)
362 self.resources[name] = {
363 'type': 'OS::Nova::Server'
366 server_properties = {
370 'networks': [] # list of dictionaries
374 self.resources[name]['depends_on'] = [key_name]
375 server_properties['key_name'] = {'get_resource': key_name}
378 self.resources[name]['depends_on'] = ports
381 server_properties['networks'].append(
382 {'port': {'get_resource': port}}
386 for i in range(len(networks)):
387 server_properties['networks'].append({'network': networks[i]})
390 server_properties['scheduler_hints'] = scheduler_hints
393 server_properties['user_data'] = user_data
396 assert type(metadata) is dict
397 server_properties['metadata'] = metadata
399 if additional_properties:
400 assert type(additional_properties) is dict
401 for prop in additional_properties:
402 server_properties[prop] = additional_properties[prop]
404 server_properties['config_drive'] = True
406 self.resources[name]['properties'] = server_properties
408 self._template['outputs'][name] = {
409 'description': 'VM UUID',
410 'value': {'get_resource': name}
413 def create(self, block=True):
414 '''creates a template in the target cloud using heat
415 returns a dict with the requested output values from the template'''
416 log.info("Creating stack '%s'", self.name)
418 # create stack early to support cleanup, e.g. ctrl-c while waiting
419 stack = HeatStack(self.name)
421 heat = self._get_heat_client()
422 json_template = json.dumps(self._template)
423 start_time = time.time()
424 stack.uuid = self.uuid = heat.stacks.create(
425 stack_name=self.name, template=json_template,
426 parameters=self.heat_parameters)['stack']['id']
428 status = self.status()
431 while status != u'CREATE_COMPLETE':
432 log.debug("stack state %s", status)
433 if status == u'CREATE_FAILED':
434 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
435 'stack_status_reason'))
438 status = self.status()
440 end_time = time.time()
441 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
443 for output in outputs:
444 self.outputs[output["output_key"].encode("ascii")] = \
445 output["output_value"].encode("ascii")
447 log.info("Created stack '%s' in %d secs",
448 self.name, end_time - start_time)
450 stack.outputs = self.outputs