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