e32d360e405570b25f6d85c2226bced69ce51284
[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 import time
13 import datetime
14 import getpass
15 import socket
16 import logging
17 import json
18
19 from oslo_utils import encodeutils
20 import heatclient
21 import pkg_resources
22
23 from yardstick.common import template_format
24 import yardstick.common.openstack_utils as op_utils
25
26
27 log = logging.getLogger(__name__)
28
29
30 HEAT_KEY_UUID_LENGTH = 8
31
32
33 def get_short_key_uuid(uuid):
34     return str(uuid)[:HEAT_KEY_UUID_LENGTH]
35
36
37 class HeatObject(object):
38     ''' base class for template and stack'''
39     def __init__(self):
40         self._heat_client = None
41         self.uuid = None
42
43     def _get_heat_client(self):
44         '''returns a heat client instance'''
45
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)
52
53         return self._heat_client
54
55     def status(self):
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')
60
61
62 class HeatStack(HeatObject):
63     ''' Represents a Heat stack (deployed template) '''
64     stacks = []
65
66     def __init__(self, name):
67         super(HeatStack, self).__init__()
68         self.uuid = None
69         self.name = name
70         self.outputs = None
71         HeatStack.stacks.append(self)
72
73     @staticmethod
74     def stacks_exist():
75         '''check if any stack has been deployed'''
76         return len(HeatStack.stacks) > 0
77
78     def _delete(self):
79         '''deletes a stack from the target cloud using heat'''
80         if self.uuid is None:
81             return
82
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()
87         template.delete()
88         status = self.status()
89
90         while status != u'DELETE_COMPLETE':
91             log.debug("stack state %s", status)
92             if status == u'DELETE_FAILED':
93                 raise RuntimeError(
94                     heat.stacks.get(self.uuid).stack_status_reason)
95
96             time.sleep(2)
97             status = self.status()
98
99         end_time = time.time()
100         log.info("Deleted stack '%s' in %d secs", self.name,
101                  end_time - start_time)
102         self.uuid = None
103
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.
108         '''
109         if self.uuid is None:
110             return
111
112         if not block:
113             self._delete()
114             return
115
116         i = 0
117         while i < retries:
118             try:
119                 self._delete()
120                 break
121             except RuntimeError as err:
122                 log.warn(err.args)
123                 time.sleep(2)
124             i += 1
125
126         # if still not deleted try once more and let it fail everything
127         if self.uuid is not None:
128             self._delete()
129
130         HeatStack.stacks.remove(self)
131
132     @staticmethod
133     def delete_all():
134         for stack in HeatStack.stacks[:]:
135             stack.delete()
136
137     def update(self):
138         '''update a stack'''
139         raise RuntimeError("not implemented")
140
141
142 class HeatTemplate(HeatObject):
143     '''Describes a Heat template and a method to deploy template to a stack'''
144
145     def _init_template(self):
146         self._template = {}
147         self._template['heat_template_version'] = '2013-05-23'
148
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)
155
156         # short hand for resources part of template
157         self.resources = self._template['resources'] = {}
158
159         self._template['outputs'] = {}
160
161     def __init__(self, name, template_file=None, heat_parameters=None):
162         super(HeatTemplate, self).__init__()
163         self.name = name
164         self.state = "NOT_CREATED"
165         self.keystone_client = None
166         self.heat_client = None
167         self.heat_parameters = {}
168
169         # heat_parameters is passed to heat in stack create, empty dict when
170         # yardstick creates the template (no get_param in resources part)
171         if heat_parameters:
172             self.heat_parameters = heat_parameters
173
174         if template_file:
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
180         else:
181             self._init_template()
182
183         # holds results of requested output after deployment
184         self.outputs = {}
185
186         log.debug("template object '%s' created", name)
187
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}
194         }
195
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'",
199                   name, network, cidr)
200         self.resources[name] = {
201             'type': 'OS::Neutron::Subnet',
202             'depends_on': network,
203             'properties': {
204                 'name': name,
205                 'cidr': cidr,
206                 'network_id': {'get_resource': network}
207             }
208         }
209
210         self._template['outputs'][name] = {
211             'description': 'subnet %s ID' % name,
212             'value': {'get_resource': name}
213         }
214
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)
218
219         self.resources[name] = {
220             'type': 'OS::Neutron::Router',
221             'depends_on': [subnet_name],
222             'properties': {
223                 'name': name,
224                 'external_gateway_info': {
225                     'network': ext_gw_net
226                 }
227             }
228         }
229
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)
234
235         self.resources[name] = {
236             'type': 'OS::Neutron::RouterInterface',
237             'depends_on': [router_name, subnet_name],
238             'properties': {
239                 'router_id': {'get_resource': router_name},
240                 'subnet_id': {'get_resource': subnet_name}
241             }
242         }
243
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],
251             'properties': {
252                 'name': name,
253                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
254                 'network_id': {'get_resource': network_name},
255                 'replacement_policy': 'AUTO',
256             }
257         }
258
259         if sec_group_id:
260             self.resources[name]['depends_on'].append(sec_group_id)
261             self.resources[name]['properties']['security_groups'] = \
262                 [sec_group_id]
263
264         self._template['outputs'][name] = {
265             'description': 'Address for interface %s' % name,
266             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
267         }
268
269     def add_floating_ip(self, name, network_name, port_name, router_if_name,
270                         secgroup_name=None):
271         '''add to the template a Nova FloatingIP resource
272         see: https://bugs.launchpad.net/heat/+bug/1299259
273         '''
274         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
275                   "rif '%s'", name, network_name, port_name, router_if_name)
276
277         self.resources[name] = {
278             'type': 'OS::Nova::FloatingIP',
279             'depends_on': [port_name, router_if_name],
280             'properties': {
281                 'pool': network_name
282             }
283         }
284
285         if secgroup_name:
286             self.resources[name]["depends_on"].append(secgroup_name)
287
288         self._template['outputs'][name] = {
289             'description': 'floating ip %s' % name,
290             'value': {'get_attr': [name, 'ip']}
291         }
292
293     def add_floating_ip_association(self, name, floating_ip_name, port_name):
294         '''add to the template a Nova FloatingIP Association resource
295         '''
296         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
297                   "floating_ip '%s'", name, port_name, floating_ip_name)
298
299         self.resources[name] = {
300             'type': 'OS::Neutron::FloatingIPAssociation',
301             'depends_on': [port_name],
302             'properties': {
303                 'floatingip_id': {'get_resource': floating_ip_name},
304                 'port_id': {'get_resource': port_name}
305             }
306         }
307
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',
313             'properties': {
314                 'name': name,
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'),
320                     'utf-8')
321             }
322         }
323
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)
329
330         self.resources[name] = {
331             'type': 'OS::Nova::ServerGroup',
332             'properties': {
333                 'name': name,
334                 'policies': [policy]
335             }
336         }
337
338         self._template['outputs'][name] = {
339             'description': 'ID Server Group %s' % name,
340             'value': {'get_resource': name}
341         }
342
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',
348             'properties': {
349                 'name': name,
350                 'description': "Group allowing icmp and upd/tcp on all ports",
351                 'rules': [
352                     {'remote_ip_prefix': '0.0.0.0/0',
353                      'protocol': 'tcp',
354                      'port_range_min': '1',
355                      'port_range_max': '65535'},
356                     {'remote_ip_prefix': '0.0.0.0/0',
357                      'protocol': 'udp',
358                      'port_range_min': '1',
359                      'port_range_max': '65535'},
360                     {'remote_ip_prefix': '0.0.0.0/0',
361                      'protocol': 'icmp'}
362                 ]
363             }
364         }
365
366         self._template['outputs'][name] = {
367             'description': 'ID of Security Group',
368             'value': {'get_resource': name}
369         }
370
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)
377
378         self.resources[name] = {
379             'type': 'OS::Nova::Server'
380         }
381
382         server_properties = {
383             'name': name,
384             'image': image,
385             'flavor': flavor,
386             'networks': []  # list of dictionaries
387         }
388
389         if user:
390             server_properties['admin_user'] = user
391
392         if key_name:
393             self.resources[name]['depends_on'] = [key_name]
394             server_properties['key_name'] = {'get_resource': key_name}
395
396         if ports:
397             self.resources[name]['depends_on'] = ports
398
399             for port in ports:
400                 server_properties['networks'].append(
401                     {'port': {'get_resource': port}}
402                 )
403
404         if networks:
405             for i in range(len(networks)):
406                 server_properties['networks'].append({'network': networks[i]})
407
408         if scheduler_hints:
409             server_properties['scheduler_hints'] = scheduler_hints
410
411         if user_data:
412             server_properties['user_data'] = user_data
413
414         if metadata:
415             assert type(metadata) is dict
416             server_properties['metadata'] = metadata
417
418         if additional_properties:
419             assert type(additional_properties) is dict
420             for prop in additional_properties:
421                 server_properties[prop] = additional_properties[prop]
422
423         server_properties['config_drive'] = True
424
425         self.resources[name]['properties'] = server_properties
426
427         self._template['outputs'][name] = {
428             'description': 'VM UUID',
429             'value': {'get_resource': name}
430         }
431
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)
436
437         # create stack early to support cleanup, e.g. ctrl-c while waiting
438         stack = HeatStack(self.name)
439
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']
446
447         status = self.status()
448
449         if block:
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'))
455
456                 time.sleep(2)
457                 status = self.status()
458
459             end_time = time.time()
460             outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
461
462         for output in outputs:
463             self.outputs[output["output_key"].encode("ascii")] = \
464                 output["output_value"].encode("ascii")
465
466         log.info("Created stack '%s' in %d secs",
467                  self.name, end_time - start_time)
468
469         stack.outputs = self.outputs
470         return stack