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