ddab89640e1d0c26bc3efc18c99b8fe0ac246a2c
[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 log = logging.getLogger(__name__)
25
26
27 class HeatObject(object):
28     ''' base class for template and stack'''
29     def __init__(self):
30         self._keystone_client = None
31         self._heat_client = None
32         self.uuid = None
33
34     def _get_keystone_client(self):
35         '''returns a keystone client instance'''
36
37         if self._keystone_client is None:
38             self._keystone_client = keystoneclient.v2_0.client.Client(
39                 auth_url=os.environ.get('OS_AUTH_URL'),
40                 username=os.environ.get('OS_USERNAME'),
41                 password=os.environ.get('OS_PASSWORD'),
42                 tenant_name=os.environ.get('OS_TENANT_NAME'))
43
44         return self._keystone_client
45
46     def _get_heat_client(self):
47         '''returns a heat client instance'''
48
49         if self._heat_client is None:
50             keystone = self._get_keystone_client()
51             heat_endpoint = keystone.service_catalog.url_for(
52                 service_type='orchestration')
53             self._heat_client = heatclient.client.Client(
54                 '1', endpoint=heat_endpoint, token=keystone.auth_token)
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.warn(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__(self, name):
149         super(HeatTemplate, self).__init__()
150         self.name = name
151         self.state = "NOT_CREATED"
152         self.keystone_client = None
153         self.heat_client = None
154
155         # Heat template
156         self._template = {}
157         self._template['heat_template_version'] = '2013-05-23'
158
159         timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
160         self._template['description'] = \
161             '''Stack built by the yardstick framework for %s on host %s %s.
162             All referred generated resources are prefixed with the template
163             name (i.e. %s).''' % (getpass.getuser(), socket.gethostname(),
164                                   timestamp, name)
165
166         # short hand for resources part of template
167         self.resources = self._template['resources'] = {}
168
169         self._template['outputs'] = {}
170
171         # holds results of requested output after deployment
172         self.outputs = {}
173
174         log.debug("template object '%s' created", name)
175
176     def add_network(self, name):
177         '''add to the template a Neutron Net'''
178         log.debug("adding Neutron::Net '%s'", name)
179         self.resources[name] = {
180             'type': 'OS::Neutron::Net',
181             'properties': {'name': name}
182         }
183
184     def add_subnet(self, name, network, cidr):
185         '''add to the template a Neutron Subnet'''
186         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
187                   name, network, cidr)
188         self.resources[name] = {
189             'type': 'OS::Neutron::Subnet',
190             'depends_on': network,
191             'properties': {
192                 'name': name,
193                 'cidr': cidr,
194                 'network_id': {'get_resource': network}
195             }
196         }
197
198         self._template['outputs'][name] = {
199             'description': 'subnet %s ID' % name,
200             'value': {'get_resource': name}
201         }
202
203     def add_router(self, name, ext_gw_net, subnet_name):
204         '''add to the template a Neutron Router and interface'''
205         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
206
207         self.resources[name] = {
208             'type': 'OS::Neutron::Router',
209             'depends_on': [subnet_name],
210             'properties': {
211                 'name': name,
212                 'external_gateway_info': {
213                     'network': ext_gw_net
214                 }
215             }
216         }
217
218     def add_router_interface(self, name, router_name, subnet_name):
219         '''add to the template a Neutron RouterInterface and interface'''
220         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
221                   "subnet:'%s'", name, router_name, subnet_name)
222
223         self.resources[name] = {
224             'type': 'OS::Neutron::RouterInterface',
225             'depends_on': [router_name, subnet_name],
226             'properties': {
227                 'router_id': {'get_resource': router_name},
228                 'subnet_id': {'get_resource': subnet_name}
229             }
230         }
231
232     def add_port(self, name, network_name, subnet_name, sec_group_id=None):
233         '''add to the template a named Neutron Port'''
234         log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
235                   "secgroup:%s", name, network_name, subnet_name, sec_group_id)
236         self.resources[name] = {
237             'type': 'OS::Neutron::Port',
238             'depends_on': [subnet_name],
239             'properties': {
240                 'name': name,
241                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
242                 'network': network_name,
243                 'replacement_policy': 'AUTO',
244             }
245         }
246
247         if sec_group_id:
248             self.resources[name]['depends_on'].append(sec_group_id)
249             self.resources[name]['properties']['security_groups'] = \
250                 [sec_group_id]
251
252         self._template['outputs'][name] = {
253             'description': 'Address for interface %s' % name,
254             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
255         }
256
257     def add_floating_ip(self, name, network_name, port_name, router_if_name,
258                         secgroup_name=None):
259         '''add to the template a Neutron FloatingIP resource
260         see: https://bugs.launchpad.net/heat/+bug/1299259
261         '''
262         log.debug("adding Neutron::FloatingIP '%s', network '%s', port '%s', "
263                   "rif '%s'", name, network_name, port_name, router_if_name)
264
265         self.resources[name] = {
266             'type': 'OS::Neutron::FloatingIP',
267             'depends_on': [port_name, router_if_name],
268             'properties': {
269                 'floating_network': network_name,
270                 'port_id': {'get_resource': port_name}
271             }
272         }
273
274         if secgroup_name:
275             self.resources[name]["depends_on"].append(secgroup_name)
276
277         self._template['outputs'][name] = {
278             'description': 'floating ip %s' % name,
279             'value': {'get_attr': [name, 'floating_ip_address']}
280         }
281
282     def add_keypair(self, name):
283         '''add to the template a Nova KeyPair'''
284         log.debug("adding Nova::KeyPair '%s'", name)
285         self.resources[name] = {
286             'type': 'OS::Nova::KeyPair',
287             'properties': {
288                 'name': name,
289                 'public_key': pkg_resources.resource_string(
290                     'yardstick.resources', 'files/yardstick_key.pub')
291             }
292         }
293
294     def add_servergroup(self, name, policy):
295         '''add to the template a Nova ServerGroup'''
296         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
297         if policy not in ["anti-affinity", "affinity"]:
298             raise ValueError(policy)
299
300         self.resources[name] = {
301             'type': 'OS::Nova::ServerGroup',
302             'properties': {
303                 'name': name,
304                 'policies': [policy]
305             }
306         }
307
308         self._template['outputs'][name] = {
309             'description': 'ID Server Group %s' % name,
310             'value': {'get_resource': name}
311         }
312
313     def add_security_group(self, name):
314         '''add to the template a Neutron SecurityGroup'''
315         log.debug("adding Neutron::SecurityGroup '%s'", name)
316         self.resources[name] = {
317             'type': 'OS::Neutron::SecurityGroup',
318             'properties': {
319                 'name': name,
320                 'description': "Group allowing icmp and upd/tcp on all ports",
321                 'rules': [
322                     {'remote_ip_prefix': '0.0.0.0/0',
323                      'protocol': 'tcp'},
324                     {'remote_ip_prefix': '0.0.0.0/0',
325                      'protocol': 'udp'},
326                     {'remote_ip_prefix': '0.0.0.0/0',
327                      'protocol': 'icmp'}
328                 ]
329             }
330         }
331
332         self._template['outputs'][name] = {
333             'description': 'ID of Security Group',
334             'value': {'get_resource': name}
335         }
336
337     def add_server(self, name, image, flavor, ports=None, networks=None,
338                    scheduler_hints=None, key_name=None, user_data=None,
339                    metadata=None, additional_properties=None):
340         '''add to the template a Nova Server'''
341         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
342                   "ports %s", name, image, flavor, ports)
343
344         self.resources[name] = {
345             'type': 'OS::Nova::Server'
346         }
347
348         server_properties = {
349             'name': name,
350             'image': image,
351             'flavor': flavor,
352             'networks': []  # list of dictionaries
353         }
354
355         if key_name:
356             self.resources[name]['depends_on'] = [key_name]
357             server_properties['key_name'] = {'get_resource': key_name}
358
359         if ports:
360             self.resources[name]['depends_on'] = ports
361
362             for port in ports:
363                 server_properties['networks'].append(
364                     {'port': {'get_resource': port}}
365                 )
366
367         if networks:
368             for i in range(len(networks)):
369                 server_properties['networks'].append({'network': networks[i]})
370
371         if scheduler_hints:
372             server_properties['scheduler_hints'] = scheduler_hints
373
374         if user_data:
375             server_properties['user_data'] = user_data
376
377         if metadata:
378             assert type(metadata) is dict
379             server_properties['metadata'] = metadata
380
381         if additional_properties:
382             assert type(additional_properties) is dict
383             for prop in additional_properties:
384                 server_properties[prop] = additional_properties[prop]
385
386         server_properties['config_drive'] = True
387
388         self.resources[name]['properties'] = server_properties
389
390         self._template['outputs'][name] = {
391             'description': 'VM UUID',
392             'value': {'get_resource': name}
393         }
394
395     def create(self, block=True):
396         '''creates a template in the target cloud using heat
397         returns a dict with the requested output values from the template'''
398         log.info("Creating stack '%s'", self.name)
399
400         # create stack early to support cleanup, e.g. ctrl-c while waiting
401         stack = HeatStack(self.name)
402
403         heat = self._get_heat_client()
404         json_template = json.dumps(self._template)
405         start_time = time.time()
406         stack.uuid = self.uuid = heat.stacks.create(
407             stack_name=self.name, template=json_template)['stack']['id']
408
409         status = self.status()
410
411         if block:
412             while status != u'CREATE_COMPLETE':
413                 log.debug("stack state %s", status)
414                 if status == u'CREATE_FAILED':
415                     raise RuntimeError(getattr(heat.stacks.get(self.uuid),
416                                                'stack_status_reason'))
417
418                 time.sleep(2)
419                 status = self.status()
420
421             end_time = time.time()
422             outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
423
424         for output in outputs:
425             self.outputs[output["output_key"].encode("ascii")] = \
426                 output["output_value"].encode("ascii")
427
428         log.info("Created stack '%s' in %d secs",
429                  self.name, end_time - start_time)
430
431         stack.outputs = self.outputs
432         return stack