a3179a6f11de6c60889cac7e8a6a25f0f599bed1
[yardstick.git] / yardstick / orchestrator / heat.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 #
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 ##############################################################################
9
10 """ Heat template and stack management
11 """
12
13 import os
14 import time
15 import datetime
16 import getpass
17 import socket
18 import logging
19 import pkg_resources
20 import json
21 import heatclient.client
22 import keystoneclient
23
24 from yardstick.common import template_format
25
26
27 log = logging.getLogger(__name__)
28
29
30 class HeatObject(object):
31     ''' base class for template and stack'''
32     def __init__(self):
33         self._keystone_client = None
34         self._heat_client = None
35         self.uuid = None
36
37     def _get_keystone_client(self):
38         '''returns a keystone client instance'''
39
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'))
46
47         return self._keystone_client
48
49     def _get_heat_client(self):
50         '''returns a heat client instance'''
51
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)
58
59         return self._heat_client
60
61     def status(self):
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')
66
67
68 class HeatStack(HeatObject):
69     ''' Represents a Heat stack (deployed template) '''
70     stacks = []
71
72     def __init__(self, name):
73         super(HeatStack, self).__init__()
74         self.uuid = None
75         self.name = name
76         self.outputs = None
77         HeatStack.stacks.append(self)
78
79     @staticmethod
80     def stacks_exist():
81         '''check if any stack has been deployed'''
82         return len(HeatStack.stacks) > 0
83
84     def _delete(self):
85         '''deletes a stack from the target cloud using heat'''
86         if self.uuid is None:
87             return
88
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()
93         template.delete()
94         status = self.status()
95
96         while status != u'DELETE_COMPLETE':
97             log.debug("stack state %s", status)
98             if status == u'DELETE_FAILED':
99                 raise RuntimeError(
100                     heat.stacks.get(self.uuid).stack_status_reason)
101
102             time.sleep(2)
103             status = self.status()
104
105         end_time = time.time()
106         log.info("Deleted stack '%s' in %d secs", self.name,
107                  end_time - start_time)
108         self.uuid = None
109
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.
114         '''
115         if self.uuid is None:
116             return
117
118         if not block:
119             self._delete()
120             return
121
122         i = 0
123         while i < retries:
124             try:
125                 self._delete()
126                 break
127             except RuntimeError as err:
128                 log.warn(err.args)
129                 time.sleep(2)
130             i += 1
131
132         # if still not deleted try once more and let it fail everything
133         if self.uuid is not None:
134             self._delete()
135
136         HeatStack.stacks.remove(self)
137
138     @staticmethod
139     def delete_all():
140         for stack in HeatStack.stacks[:]:
141             stack.delete()
142
143     def update(self):
144         '''update a stack'''
145         raise RuntimeError("not implemented")
146
147
148 class HeatTemplate(HeatObject):
149     '''Describes a Heat template and a method to deploy template to a stack'''
150
151     def _init_template(self):
152         self._template = {}
153         self._template['heat_template_version'] = '2013-05-23'
154
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)
161
162         # short hand for resources part of template
163         self.resources = self._template['resources'] = {}
164
165         self._template['outputs'] = {}
166
167     def __init__(self, name, template_file=None, heat_parameters=None):
168         super(HeatTemplate, self).__init__()
169         self.name = name
170         self.state = "NOT_CREATED"
171         self.keystone_client = None
172         self.heat_client = None
173         self.heat_parameters = {}
174
175         # heat_parameters is passed to heat in stack create, empty dict when
176         # yardstick creates the template (no get_param in resources part)
177         if heat_parameters:
178             self.heat_parameters = heat_parameters
179
180         if template_file:
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
186         else:
187             self._init_template()
188
189         # holds results of requested output after deployment
190         self.outputs = {}
191
192         log.debug("template object '%s' created", name)
193
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}
200         }
201
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'",
205                   name, network, cidr)
206         self.resources[name] = {
207             'type': 'OS::Neutron::Subnet',
208             'depends_on': network,
209             'properties': {
210                 'name': name,
211                 'cidr': cidr,
212                 'network_id': {'get_resource': network}
213             }
214         }
215
216         self._template['outputs'][name] = {
217             'description': 'subnet %s ID' % name,
218             'value': {'get_resource': name}
219         }
220
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)
224
225         self.resources[name] = {
226             'type': 'OS::Neutron::Router',
227             'depends_on': [subnet_name],
228             'properties': {
229                 'name': name,
230                 'external_gateway_info': {
231                     'network': ext_gw_net
232                 }
233             }
234         }
235
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)
240
241         self.resources[name] = {
242             'type': 'OS::Neutron::RouterInterface',
243             'depends_on': [router_name, subnet_name],
244             'properties': {
245                 'router_id': {'get_resource': router_name},
246                 'subnet_id': {'get_resource': subnet_name}
247             }
248         }
249
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],
257             'properties': {
258                 'name': name,
259                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
260                 'network': network_name,
261                 'replacement_policy': 'AUTO',
262             }
263         }
264
265         if sec_group_id:
266             self.resources[name]['depends_on'].append(sec_group_id)
267             self.resources[name]['properties']['security_groups'] = \
268                 [sec_group_id]
269
270         self._template['outputs'][name] = {
271             'description': 'Address for interface %s' % name,
272             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
273         }
274
275     def add_floating_ip(self, name, network_name, port_name, router_if_name,
276                         secgroup_name=None):
277         '''add to the template a Neutron FloatingIP resource
278         see: https://bugs.launchpad.net/heat/+bug/1299259
279         '''
280         log.debug("adding Neutron::FloatingIP '%s', network '%s', port '%s', "
281                   "rif '%s'", name, network_name, port_name, router_if_name)
282
283         self.resources[name] = {
284             'type': 'OS::Neutron::FloatingIP',
285             'depends_on': [port_name, router_if_name],
286             'properties': {
287                 'floating_network': network_name,
288                 'port_id': {'get_resource': port_name}
289             }
290         }
291
292         if secgroup_name:
293             self.resources[name]["depends_on"].append(secgroup_name)
294
295         self._template['outputs'][name] = {
296             'description': 'floating ip %s' % name,
297             'value': {'get_attr': [name, 'floating_ip_address']}
298         }
299
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',
305             'properties': {
306                 'name': name,
307                 'public_key': pkg_resources.resource_string(
308                     'yardstick.resources', 'files/yardstick_key.pub')
309             }
310         }
311
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)
317
318         self.resources[name] = {
319             'type': 'OS::Nova::ServerGroup',
320             'properties': {
321                 'name': name,
322                 'policies': [policy]
323             }
324         }
325
326         self._template['outputs'][name] = {
327             'description': 'ID Server Group %s' % name,
328             'value': {'get_resource': name}
329         }
330
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',
336             'properties': {
337                 'name': name,
338                 'description': "Group allowing icmp and upd/tcp on all ports",
339                 'rules': [
340                     {'remote_ip_prefix': '0.0.0.0/0',
341                      'protocol': 'tcp'},
342                     {'remote_ip_prefix': '0.0.0.0/0',
343                      'protocol': 'udp'},
344                     {'remote_ip_prefix': '0.0.0.0/0',
345                      'protocol': 'icmp'}
346                 ]
347             }
348         }
349
350         self._template['outputs'][name] = {
351             'description': 'ID of Security Group',
352             'value': {'get_resource': name}
353         }
354
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)
361
362         self.resources[name] = {
363             'type': 'OS::Nova::Server'
364         }
365
366         server_properties = {
367             'name': name,
368             'image': image,
369             'flavor': flavor,
370             'networks': []  # list of dictionaries
371         }
372
373         if key_name:
374             self.resources[name]['depends_on'] = [key_name]
375             server_properties['key_name'] = {'get_resource': key_name}
376
377         if ports:
378             self.resources[name]['depends_on'] = ports
379
380             for port in ports:
381                 server_properties['networks'].append(
382                     {'port': {'get_resource': port}}
383                 )
384
385         if networks:
386             for i in range(len(networks)):
387                 server_properties['networks'].append({'network': networks[i]})
388
389         if scheduler_hints:
390             server_properties['scheduler_hints'] = scheduler_hints
391
392         if user_data:
393             server_properties['user_data'] = user_data
394
395         if metadata:
396             assert type(metadata) is dict
397             server_properties['metadata'] = metadata
398
399         if additional_properties:
400             assert type(additional_properties) is dict
401             for prop in additional_properties:
402                 server_properties[prop] = additional_properties[prop]
403
404         server_properties['config_drive'] = True
405
406         self.resources[name]['properties'] = server_properties
407
408         self._template['outputs'][name] = {
409             'description': 'VM UUID',
410             'value': {'get_resource': name}
411         }
412
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)
417
418         # create stack early to support cleanup, e.g. ctrl-c while waiting
419         stack = HeatStack(self.name)
420
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']
427
428         status = self.status()
429
430         if block:
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'))
436
437                 time.sleep(2)
438                 status = self.status()
439
440             end_time = time.time()
441             outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
442
443         for output in outputs:
444             self.outputs[output["output_key"].encode("ascii")] = \
445                 output["output_value"].encode("ascii")
446
447         log.info("Created stack '%s' in %d secs",
448                  self.name, end_time - start_time)
449
450         stack.outputs = self.outputs
451         return stack