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 log = logging.getLogger(__name__)
27 class HeatObject(object):
28 ''' base class for template and stack'''
30 self._keystone_client = None
31 self._heat_client = None
34 def _get_keystone_client(self):
35 '''returns a keystone client instance'''
37 if self._keystone_client is None:
38 self._keystone_client = keystoneclient.v2_0.client.Client(
39 auth_url=os.environ.get('OS_AUTH_URL'),
40 username=os.environ.get('OS_USERNAME'),
41 password=os.environ.get('OS_PASSWORD'),
42 tenant_name=os.environ.get('OS_TENANT_NAME'))
44 return self._keystone_client
46 def _get_heat_client(self):
47 '''returns a heat client instance'''
49 if self._heat_client is None:
50 keystone = self._get_keystone_client()
51 heat_endpoint = keystone.service_catalog.url_for(
52 service_type='orchestration')
53 self._heat_client = heatclient.client.Client(
54 '1', endpoint=heat_endpoint, token=keystone.auth_token)
56 return self._heat_client
59 '''returns stack state as a string'''
60 heat = self._get_heat_client()
61 stack = heat.stacks.get(self.uuid)
62 return getattr(stack, 'stack_status')
65 class HeatStack(HeatObject):
66 ''' Represents a Heat stack (deployed template) '''
69 def __init__(self, uuid, name):
70 super(HeatStack, self).__init__()
74 HeatStack.stacks.append(self)
78 '''check if any stack has been deployed'''
79 return len(HeatStack.stacks) > 0
82 '''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__(self, name):
146 super(HeatTemplate, self).__init__()
148 self.state = "NOT_CREATED"
149 self.keystone_client = None
150 self.heat_client = None
154 self._template['heat_template_version'] = '2013-05-23'
156 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
157 self._template['description'] = \
158 '''Stack built by the yardstick framework for %s on host %s %s.
159 All referred generated resources are prefixed with the template
160 name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
163 # short hand for resources part of template
164 self.resources = self._template['resources'] = {}
166 self._template['outputs'] = {}
168 # holds results of requested output after deployment
171 log.debug("template object '%s' created", name)
173 def add_network(self, name):
174 '''add to the template a Neutron Net'''
175 log.debug("adding Neutron::Net '%s'", name)
176 self.resources[name] = {
177 'type': 'OS::Neutron::Net',
178 'properties': {'name': name}
181 def add_subnet(self, name, network, cidr):
182 '''add to the template a Neutron Subnet'''
183 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
185 self.resources[name] = {
186 'type': 'OS::Neutron::Subnet',
187 'depends_on': network,
191 'network_id': {'get_resource': network}
195 self._template['outputs'][name] = {
196 'description': 'subnet %s ID' % name,
197 'value': {'get_resource': name}
200 def add_router(self, name, ext_gw_net, subnet_name):
201 '''add to the template a Neutron Router and interface'''
202 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
204 self.resources[name] = {
205 'type': 'OS::Neutron::Router',
206 'depends_on': [subnet_name],
209 'external_gateway_info': {
210 'network': ext_gw_net
215 def add_router_interface(self, name, router_name, subnet_name):
216 '''add to the template a Neutron RouterInterface and interface'''
217 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
218 "subnet:'%s'", name, router_name, subnet_name)
220 self.resources[name] = {
221 'type': 'OS::Neutron::RouterInterface',
222 'depends_on': [router_name, subnet_name],
224 'router_id': {'get_resource': router_name},
225 'subnet_id': {'get_resource': subnet_name}
229 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
230 '''add to the template a named Neutron Port'''
231 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
232 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
233 self.resources[name] = {
234 'type': 'OS::Neutron::Port',
235 'depends_on': [subnet_name],
238 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
239 'network': network_name,
240 'replacement_policy': 'AUTO',
245 self.resources[name]['depends_on'].append(sec_group_id)
246 self.resources[name]['properties']['security_groups'] = \
249 self._template['outputs'][name] = {
250 'description': 'Address for interface %s' % name,
251 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
254 def add_floating_ip(self, name, network_name, port_name, router_if_name,
256 '''add to the template a Neutron FloatingIP resource
257 see: https://bugs.launchpad.net/heat/+bug/1299259
259 log.debug("adding Neutron::FloatingIP '%s', network '%s', port '%s', "
260 "rif '%s'", name, network_name, port_name, router_if_name)
262 self.resources[name] = {
263 'type': 'OS::Neutron::FloatingIP',
264 'depends_on': [port_name, router_if_name],
266 'floating_network': network_name,
267 'port_id': {'get_resource': port_name}
272 self.resources[name]["depends_on"].append(secgroup_name)
274 self._template['outputs'][name] = {
275 'description': 'floating ip %s' % name,
276 'value': {'get_attr': [name, 'floating_ip_address']}
279 def add_keypair(self, name):
280 '''add to the template a Nova KeyPair'''
281 log.debug("adding Nova::KeyPair '%s'", name)
282 self.resources[name] = {
283 'type': 'OS::Nova::KeyPair',
286 'public_key': pkg_resources.resource_string(
287 'yardstick.resources', 'files/yardstick_key.pub')
291 def add_servergroup(self, name, policy):
292 '''add to the template a Nova ServerGroup'''
293 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
294 if policy not in ["anti-affinity", "affinity"]:
295 raise ValueError(policy)
297 self.resources[name] = {
298 'type': 'OS::Nova::ServerGroup',
305 self._template['outputs'][name] = {
306 'description': 'ID Server Group %s' % name,
307 'value': {'get_resource': name}
310 def add_security_group(self, name):
311 '''add to the template a Neutron SecurityGroup'''
312 log.debug("adding Neutron::SecurityGroup '%s'", name)
313 self.resources[name] = {
314 'type': 'OS::Neutron::SecurityGroup',
317 'description': "Group allowing icmp and upd/tcp on all ports",
319 {'remote_ip_prefix': '0.0.0.0/0',
321 {'remote_ip_prefix': '0.0.0.0/0',
323 {'remote_ip_prefix': '0.0.0.0/0',
329 self._template['outputs'][name] = {
330 'description': 'ID of Security Group',
331 'value': {'get_resource': name}
334 def add_server(self, name, image, flavor, ports=None, networks=None,
335 scheduler_hints=None, key_name=None, user_data=None,
336 metadata=None, additional_properties=None):
337 '''add to the template a Nova Server'''
338 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
339 "ports %s", name, image, flavor, ports)
341 self.resources[name] = {
342 'type': 'OS::Nova::Server'
345 server_properties = {
349 'networks': [] # list of dictionaries
353 self.resources[name]['depends_on'] = [key_name]
354 server_properties['key_name'] = {'get_resource': key_name}
357 self.resources[name]['depends_on'] = ports
360 server_properties['networks'].append(
361 {'port': {'get_resource': port}}
365 for i in range(len(networks)):
366 server_properties['networks'].append({'network': networks[i]})
369 server_properties['scheduler_hints'] = scheduler_hints
372 server_properties['user_data'] = user_data
375 assert type(metadata) is dict
376 server_properties['metadata'] = metadata
378 if additional_properties:
379 assert type(additional_properties) is dict
380 for prop in additional_properties:
381 server_properties[prop] = additional_properties[prop]
383 server_properties['config_drive'] = True
385 self.resources[name]['properties'] = server_properties
387 self._template['outputs'][name] = {
388 'description': 'VM UUID',
389 'value': {'get_resource': name}
392 def create(self, block=True):
393 '''creates a template in the target cloud using heat
394 returns a dict with the requested output values from the template'''
395 log.info("Creating stack '%s'", self.name)
397 heat = self._get_heat_client()
398 json_template = json.dumps(self._template)
399 start_time = time.time()
400 self.uuid = heat.stacks.create(stack_name=self.name,
401 template=json_template)['stack']['id']
403 # create stack early to support cleanup, e.g. ctrl-c while waiting
404 stack = HeatStack(self.uuid, self.name)
406 status = self.status()
409 while status != u'CREATE_COMPLETE':
410 log.debug("stack state %s", status)
411 if status == u'CREATE_FAILED':
412 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
413 'stack_status_reason'))
416 status = self.status()
418 end_time = time.time()
419 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
421 for output in outputs:
422 self.outputs[output["output_key"].encode("ascii")] = \
423 output["output_value"].encode("ascii")
425 log.info("Created stack '%s' in %d secs",
426 self.name, end_time - start_time)
428 stack.outputs = self.outputs