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