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