Bugfix: heat: don't json encode template
[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 from __future__ import absolute_import
13 from __future__ import print_function
14
15 import collections
16 import datetime
17 import getpass
18 import logging
19 import socket
20 import time
21
22 import heatclient
23 import pkg_resources
24 from oslo_utils import encodeutils
25
26 import yardstick.common.openstack_utils as op_utils
27 from yardstick.common import template_format
28
29 log = logging.getLogger(__name__)
30
31
32 HEAT_KEY_UUID_LENGTH = 8
33
34
35 def get_short_key_uuid(uuid):
36     return str(uuid)[:HEAT_KEY_UUID_LENGTH]
37
38
39 class HeatObject(object):
40     """ base class for template and stack"""
41
42     def __init__(self):
43         self._heat_client = None
44         self.uuid = None
45
46     def _get_heat_client(self):
47         """returns a heat client instance"""
48
49         if self._heat_client is None:
50             sess = op_utils.get_session()
51             heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
52             self._heat_client = heatclient.client.Client(
53                 op_utils.get_heat_api_version(),
54                 endpoint=heat_endpoint, session=sess)
55
56         return self._heat_client
57
58     def status(self):
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')
63
64
65 class HeatStack(HeatObject):
66     """ Represents a Heat stack (deployed template) """
67     stacks = []
68
69     def __init__(self, name):
70         super(HeatStack, self).__init__()
71         self.uuid = None
72         self.name = name
73         self.outputs = None
74         HeatStack.stacks.append(self)
75
76     @staticmethod
77     def stacks_exist():
78         """check if any stack has been deployed"""
79         return len(HeatStack.stacks) > 0
80
81     def _delete(self):
82         """deletes a stack from the target cloud using heat"""
83         if self.uuid is None:
84             return
85
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()
90         template.delete()
91         status = self.status()
92
93         while status != u'DELETE_COMPLETE':
94             log.debug("stack state %s", status)
95             if status == u'DELETE_FAILED':
96                 raise RuntimeError(
97                     heat.stacks.get(self.uuid).stack_status_reason)
98
99             time.sleep(2)
100             status = self.status()
101
102         end_time = time.time()
103         log.info("Deleted stack '%s' in %d secs", self.name,
104                  end_time - start_time)
105         self.uuid = None
106
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.
111         """
112         if self.uuid is None:
113             return
114
115         if not block:
116             self._delete()
117             return
118
119         i = 0
120         while i < retries:
121             try:
122                 self._delete()
123                 break
124             except RuntimeError as err:
125                 log.warning(err.args)
126                 time.sleep(2)
127             i += 1
128
129         # if still not deleted try once more and let it fail everything
130         if self.uuid is not None:
131             self._delete()
132
133         HeatStack.stacks.remove(self)
134
135     @staticmethod
136     def delete_all():
137         for stack in HeatStack.stacks[:]:
138             stack.delete()
139
140     def update(self):
141         """update a stack"""
142         raise RuntimeError("not implemented")
143
144
145 class HeatTemplate(HeatObject):
146     """Describes a Heat template and a method to deploy template to a stack"""
147
148     def _init_template(self):
149         self._template = {}
150         self._template['heat_template_version'] = '2013-05-23'
151
152         timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
153         self._template['description'] = \
154             """Stack built by the yardstick framework for %s on host %s %s.
155             All referred generated resources are prefixed with the template
156             name (i.e. %s).""" % (getpass.getuser(), socket.gethostname(),
157                                   timestamp, self.name)
158
159         # short hand for resources part of template
160         self.resources = self._template['resources'] = {}
161
162         self._template['outputs'] = {}
163
164     def __init__(self, name, template_file=None, heat_parameters=None):
165         super(HeatTemplate, self).__init__()
166         self.name = name
167         self.state = "NOT_CREATED"
168         self.keystone_client = None
169         self.heat_client = None
170         self.heat_parameters = {}
171
172         # heat_parameters is passed to heat in stack create, empty dict when
173         # yardstick creates the template (no get_param in resources part)
174         if heat_parameters:
175             self.heat_parameters = heat_parameters
176
177         if template_file:
178             with open(template_file) as stream:
179                 print("Parsing external template:", template_file)
180                 template_str = stream.read()
181             self._template = template_format.parse(template_str)
182             self._parameters = heat_parameters
183         else:
184             self._init_template()
185
186         # holds results of requested output after deployment
187         self.outputs = {}
188
189         log.debug("template object '%s' created", name)
190
191     def add_network(self, name):
192         """add to the template a Neutron Net"""
193         log.debug("adding Neutron::Net '%s'", name)
194         self.resources[name] = {
195             'type': 'OS::Neutron::Net',
196             'properties': {'name': name}
197         }
198
199     def add_server_group(self, name, policies):     # pragma: no cover
200         """add to the template a ServerGroup"""
201         log.debug("adding Nova::ServerGroup '%s'", name)
202         policies = policies if isinstance(policies, list) else [policies]
203         self.resources[name] = {
204             'type': 'OS::Nova::ServerGroup',
205             'properties': {'name': name,
206                            'policies': policies}
207         }
208
209     def add_subnet(self, name, network, cidr):
210         """add to the template a Neutron Subnet"""
211         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
212                   name, network, cidr)
213         self.resources[name] = {
214             'type': 'OS::Neutron::Subnet',
215             'depends_on': network,
216             'properties': {
217                 'name': name,
218                 'cidr': cidr,
219                 'network_id': {'get_resource': network}
220             }
221         }
222
223         self._template['outputs'][name] = {
224             'description': 'subnet %s ID' % name,
225             'value': {'get_resource': name}
226         }
227
228     def add_router(self, name, ext_gw_net, subnet_name):
229         """add to the template a Neutron Router and interface"""
230         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
231
232         self.resources[name] = {
233             'type': 'OS::Neutron::Router',
234             'depends_on': [subnet_name],
235             'properties': {
236                 'name': name,
237                 'external_gateway_info': {
238                     'network': ext_gw_net
239                 }
240             }
241         }
242
243     def add_router_interface(self, name, router_name, subnet_name):
244         """add to the template a Neutron RouterInterface and interface"""
245         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
246                   "subnet:'%s'", name, router_name, subnet_name)
247
248         self.resources[name] = {
249             'type': 'OS::Neutron::RouterInterface',
250             'depends_on': [router_name, subnet_name],
251             'properties': {
252                 'router_id': {'get_resource': router_name},
253                 'subnet_id': {'get_resource': subnet_name}
254             }
255         }
256
257     def add_port(self, name, network_name, subnet_name, sec_group_id=None):
258         """add to the template a named Neutron Port"""
259         log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
260                   "secgroup:%s", name, network_name, subnet_name, sec_group_id)
261         self.resources[name] = {
262             'type': 'OS::Neutron::Port',
263             'depends_on': [subnet_name],
264             'properties': {
265                 'name': name,
266                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
267                 'network_id': {'get_resource': network_name},
268                 'replacement_policy': 'AUTO',
269             }
270         }
271
272         if sec_group_id:
273             self.resources[name]['depends_on'].append(sec_group_id)
274             self.resources[name]['properties']['security_groups'] = \
275                 [sec_group_id]
276
277         self._template['outputs'][name] = {
278             'description': 'Address for interface %s' % name,
279             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
280         }
281
282     def add_floating_ip(self, name, network_name, port_name, router_if_name,
283                         secgroup_name=None):
284         """add to the template a Nova FloatingIP resource
285         see: https://bugs.launchpad.net/heat/+bug/1299259
286         """
287         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
288                   "rif '%s'", name, network_name, port_name, router_if_name)
289
290         self.resources[name] = {
291             'type': 'OS::Nova::FloatingIP',
292             'depends_on': [port_name, router_if_name],
293             'properties': {
294                 'pool': network_name
295             }
296         }
297
298         if secgroup_name:
299             self.resources[name]["depends_on"].append(secgroup_name)
300
301         self._template['outputs'][name] = {
302             'description': 'floating ip %s' % name,
303             'value': {'get_attr': [name, 'ip']}
304         }
305
306     def add_floating_ip_association(self, name, floating_ip_name, port_name):
307         """add to the template a Nova FloatingIP Association resource
308         """
309         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
310                   "floating_ip '%s'", name, port_name, floating_ip_name)
311
312         self.resources[name] = {
313             'type': 'OS::Neutron::FloatingIPAssociation',
314             'depends_on': [port_name],
315             'properties': {
316                 'floatingip_id': {'get_resource': floating_ip_name},
317                 'port_id': {'get_resource': port_name}
318             }
319         }
320
321     def add_keypair(self, name, key_uuid):
322         """add to the template a Nova KeyPair"""
323         log.debug("adding Nova::KeyPair '%s'", name)
324         self.resources[name] = {
325             'type': 'OS::Nova::KeyPair',
326             'properties': {
327                 'name': name,
328                 # resource_string returns bytes, so we must decode to unicode
329                 'public_key': encodeutils.safe_decode(
330                     pkg_resources.resource_string(
331                         'yardstick.resources',
332                         'files/yardstick_key-' +
333                         get_short_key_uuid(key_uuid) + '.pub'),
334                     'utf-8')
335             }
336         }
337
338     def add_servergroup(self, name, policy):
339         """add to the template a Nova ServerGroup"""
340         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
341         if policy not in ["anti-affinity", "affinity"]:
342             raise ValueError(policy)
343
344         self.resources[name] = {
345             'type': 'OS::Nova::ServerGroup',
346             'properties': {
347                 'name': name,
348                 'policies': [policy]
349             }
350         }
351
352         self._template['outputs'][name] = {
353             'description': 'ID Server Group %s' % name,
354             'value': {'get_resource': name}
355         }
356
357     def add_security_group(self, name):
358         """add to the template a Neutron SecurityGroup"""
359         log.debug("adding Neutron::SecurityGroup '%s'", name)
360         self.resources[name] = {
361             'type': 'OS::Neutron::SecurityGroup',
362             'properties': {
363                 'name': name,
364                 'description': "Group allowing icmp and upd/tcp on all ports",
365                 'rules': [
366                     {'remote_ip_prefix': '0.0.0.0/0',
367                      'protocol': 'tcp',
368                      'port_range_min': '1',
369                      'port_range_max': '65535'},
370                     {'remote_ip_prefix': '0.0.0.0/0',
371                      'protocol': 'udp',
372                      'port_range_min': '1',
373                      'port_range_max': '65535'},
374                     {'remote_ip_prefix': '0.0.0.0/0',
375                      'protocol': 'icmp'}
376                 ]
377             }
378         }
379
380         self._template['outputs'][name] = {
381             'description': 'ID of Security Group',
382             'value': {'get_resource': name}
383         }
384
385     def add_server(self, name, image, flavor, ports=None, networks=None,
386                    scheduler_hints=None, user=None, key_name=None,
387                    user_data=None, metadata=None, additional_properties=None):
388         """add to the template a Nova Server"""
389         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
390                   "ports %s", name, image, flavor, ports)
391
392         self.resources[name] = {
393             'type': 'OS::Nova::Server'
394         }
395
396         server_properties = {
397             'name': name,
398             'image': image,
399             'flavor': flavor,
400             'networks': []  # list of dictionaries
401         }
402
403         if user:
404             server_properties['admin_user'] = user
405
406         if key_name:
407             self.resources[name]['depends_on'] = [key_name]
408             server_properties['key_name'] = {'get_resource': key_name}
409
410         if ports:
411             self.resources[name]['depends_on'] = ports
412
413             for port in ports:
414                 server_properties['networks'].append(
415                     {'port': {'get_resource': port}}
416                 )
417
418         if networks:
419             for i, _ in enumerate(networks):
420                 server_properties['networks'].append({'network': networks[i]})
421
422         if scheduler_hints:
423             server_properties['scheduler_hints'] = scheduler_hints
424
425         if user_data:
426             server_properties['user_data'] = user_data
427
428         if metadata:
429             assert isinstance(metadata, collections.Mapping)
430             server_properties['metadata'] = metadata
431
432         if additional_properties:
433             assert isinstance(additional_properties, collections.Mapping)
434             for prop in additional_properties:
435                 server_properties[prop] = additional_properties[prop]
436
437         server_properties['config_drive'] = True
438
439         self.resources[name]['properties'] = server_properties
440
441         self._template['outputs'][name] = {
442             'description': 'VM UUID',
443             'value': {'get_resource': name}
444         }
445
446     def create(self, block=True):
447         """creates a template in the target cloud using heat
448         returns a dict with the requested output values from the template"""
449         log.info("Creating stack '%s'", self.name)
450
451         # create stack early to support cleanup, e.g. ctrl-c while waiting
452         stack = HeatStack(self.name)
453
454         heat = self._get_heat_client()
455         start_time = time.time()
456         stack.uuid = self.uuid = heat.stacks.create(
457             stack_name=self.name, template=self._template,
458             parameters=self.heat_parameters)['stack']['id']
459
460         status = self.status()
461         outputs = []
462
463         if block:
464             while status != u'CREATE_COMPLETE':
465                 log.debug("stack state %s", status)
466                 if status == u'CREATE_FAILED':
467                     raise RuntimeError(getattr(heat.stacks.get(self.uuid),
468                                                'stack_status_reason'))
469
470                 time.sleep(2)
471                 status = self.status()
472
473             end_time = time.time()
474             outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
475             log.info("Created stack '%s' in %d secs",
476                      self.name, end_time - start_time)
477
478         # keep outputs as unicode
479         self.outputs = {output["output_key"]: output["output_value"] for output
480                         in outputs}
481
482         stack.outputs = self.outputs
483         return stack