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, 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'''
86 log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
87 heat = self._get_heat_client()
88 template = heat.stacks.get(self.uuid)
89 start_time = time.time()
91 status = self.status()
93 while status != u'DELETE_COMPLETE':
94 log.debug("stack state %s", status)
95 if status == u'DELETE_FAILED':
97 heat.stacks.get(self.uuid).stack_status_reason)
100 status = self.status()
102 end_time = time.time()
103 log.info("Deleted stack '%s' in %d secs", self.name,
104 end_time - start_time)
107 def delete(self, block=True, retries=3):
108 '''deletes a stack in the target cloud using heat (with retry)
109 Sometimes delete fail with "InternalServerError" and the next attempt
110 succeeds. So it is worthwhile to test a couple of times.
112 if self.uuid is None:
124 except RuntimeError as err:
129 # if still not deleted try once more and let it fail everything
130 if self.uuid is not None:
133 HeatStack.stacks.remove(self)
137 for stack in HeatStack.stacks[:]:
142 raise RuntimeError("not implemented")
145 class HeatTemplate(HeatObject):
146 '''Describes a Heat template and a method to deploy template to a stack'''
148 def __init__(self, name):
149 super(HeatTemplate, self).__init__()
151 self.state = "NOT_CREATED"
152 self.keystone_client = None
153 self.heat_client = None
157 self._template['heat_template_version'] = '2013-05-23'
159 timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
160 self._template['description'] = \
161 '''Stack built by the yardstick framework for %s on host %s %s.
162 All referred generated resources are prefixed with the template
163 name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
166 # short hand for resources part of template
167 self.resources = self._template['resources'] = {}
169 self._template['outputs'] = {}
171 # holds results of requested output after deployment
174 log.debug("template object '%s' created", name)
176 def add_network(self, name):
177 '''add to the template a Neutron Net'''
178 log.debug("adding Neutron::Net '%s'", name)
179 self.resources[name] = {
180 'type': 'OS::Neutron::Net',
181 'properties': {'name': name}
184 def add_subnet(self, name, network, cidr):
185 '''add to the template a Neutron Subnet'''
186 log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
188 self.resources[name] = {
189 'type': 'OS::Neutron::Subnet',
190 'depends_on': network,
194 'network_id': {'get_resource': network}
198 self._template['outputs'][name] = {
199 'description': 'subnet %s ID' % name,
200 'value': {'get_resource': name}
203 def add_router(self, name, ext_gw_net, subnet_name):
204 '''add to the template a Neutron Router and interface'''
205 log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
207 self.resources[name] = {
208 'type': 'OS::Neutron::Router',
209 'depends_on': [subnet_name],
212 'external_gateway_info': {
213 'network': ext_gw_net
218 def add_router_interface(self, name, router_name, subnet_name):
219 '''add to the template a Neutron RouterInterface and interface'''
220 log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
221 "subnet:'%s'", name, router_name, subnet_name)
223 self.resources[name] = {
224 'type': 'OS::Neutron::RouterInterface',
225 'depends_on': [router_name, subnet_name],
227 'router_id': {'get_resource': router_name},
228 'subnet_id': {'get_resource': subnet_name}
232 def add_port(self, name, network_name, subnet_name, sec_group_id=None):
233 '''add to the template a named Neutron Port'''
234 log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
235 "secgroup:%s", name, network_name, subnet_name, sec_group_id)
236 self.resources[name] = {
237 'type': 'OS::Neutron::Port',
238 'depends_on': [subnet_name],
241 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
242 'network': network_name,
243 'replacement_policy': 'AUTO',
248 self.resources[name]['depends_on'].append(sec_group_id)
249 self.resources[name]['properties']['security_groups'] = \
252 self._template['outputs'][name] = {
253 'description': 'Address for interface %s' % name,
254 'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
257 def add_floating_ip(self, name, network_name, port_name, router_if_name,
259 '''add to the template a Neutron FloatingIP resource
260 see: https://bugs.launchpad.net/heat/+bug/1299259
262 log.debug("adding Neutron::FloatingIP '%s', network '%s', port '%s', "
263 "rif '%s'", name, network_name, port_name, router_if_name)
265 self.resources[name] = {
266 'type': 'OS::Neutron::FloatingIP',
267 'depends_on': [port_name, router_if_name],
269 'floating_network': network_name,
270 'port_id': {'get_resource': port_name}
275 self.resources[name]["depends_on"].append(secgroup_name)
277 self._template['outputs'][name] = {
278 'description': 'floating ip %s' % name,
279 'value': {'get_attr': [name, 'floating_ip_address']}
282 def add_keypair(self, name):
283 '''add to the template a Nova KeyPair'''
284 log.debug("adding Nova::KeyPair '%s'", name)
285 self.resources[name] = {
286 'type': 'OS::Nova::KeyPair',
289 'public_key': pkg_resources.resource_string(
290 'yardstick.resources', 'files/yardstick_key.pub')
294 def add_servergroup(self, name, policy):
295 '''add to the template a Nova ServerGroup'''
296 log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
297 if policy not in ["anti-affinity", "affinity"]:
298 raise ValueError(policy)
300 self.resources[name] = {
301 'type': 'OS::Nova::ServerGroup',
308 self._template['outputs'][name] = {
309 'description': 'ID Server Group %s' % name,
310 'value': {'get_resource': name}
313 def add_security_group(self, name):
314 '''add to the template a Neutron SecurityGroup'''
315 log.debug("adding Neutron::SecurityGroup '%s'", name)
316 self.resources[name] = {
317 'type': 'OS::Neutron::SecurityGroup',
320 'description': "Group allowing icmp and upd/tcp on all ports",
322 {'remote_ip_prefix': '0.0.0.0/0',
324 {'remote_ip_prefix': '0.0.0.0/0',
326 {'remote_ip_prefix': '0.0.0.0/0',
332 self._template['outputs'][name] = {
333 'description': 'ID of Security Group',
334 'value': {'get_resource': name}
337 def add_server(self, name, image, flavor, ports=None, networks=None,
338 scheduler_hints=None, key_name=None, user_data=None,
339 metadata=None, additional_properties=None):
340 '''add to the template a Nova Server'''
341 log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
342 "ports %s", name, image, flavor, ports)
344 self.resources[name] = {
345 'type': 'OS::Nova::Server'
348 server_properties = {
352 'networks': [] # list of dictionaries
356 self.resources[name]['depends_on'] = [key_name]
357 server_properties['key_name'] = {'get_resource': key_name}
360 self.resources[name]['depends_on'] = ports
363 server_properties['networks'].append(
364 {'port': {'get_resource': port}}
368 for i in range(len(networks)):
369 server_properties['networks'].append({'network': networks[i]})
372 server_properties['scheduler_hints'] = scheduler_hints
375 server_properties['user_data'] = user_data
378 assert type(metadata) is dict
379 server_properties['metadata'] = metadata
381 if additional_properties:
382 assert type(additional_properties) is dict
383 for prop in additional_properties:
384 server_properties[prop] = additional_properties[prop]
386 server_properties['config_drive'] = True
388 self.resources[name]['properties'] = server_properties
390 self._template['outputs'][name] = {
391 'description': 'VM UUID',
392 'value': {'get_resource': name}
395 def create(self, block=True):
396 '''creates a template in the target cloud using heat
397 returns a dict with the requested output values from the template'''
398 log.info("Creating stack '%s'", self.name)
400 # create stack early to support cleanup, e.g. ctrl-c while waiting
401 stack = HeatStack(self.name)
403 heat = self._get_heat_client()
404 json_template = json.dumps(self._template)
405 start_time = time.time()
406 stack.uuid = self.uuid = heat.stacks.create(
407 stack_name=self.name, template=json_template)['stack']['id']
409 status = self.status()
412 while status != u'CREATE_COMPLETE':
413 log.debug("stack state %s", status)
414 if status == u'CREATE_FAILED':
415 raise RuntimeError(getattr(heat.stacks.get(self.uuid),
416 'stack_status_reason'))
419 status = self.status()
421 end_time = time.time()
422 outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
424 for output in outputs:
425 self.outputs[output["output_key"].encode("ascii")] = \
426 output["output_value"].encode("ascii")
428 log.info("Created stack '%s' in %d secs",
429 self.name, end_time - start_time)
431 stack.outputs = self.outputs