ea9bd1b086e08b74b407f8ec12e2bc81451a7187
[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
20 import socket
21 import time
22
23 import heatclient
24 import pkg_resources
25
26 from oslo_utils import encodeutils
27
28 import yardstick.common.openstack_utils as op_utils
29 from yardstick.common import template_format
30
31 log = logging.getLogger(__name__)
32
33
34 HEAT_KEY_UUID_LENGTH = 8
35
36 PROVIDER_SRIOV = "sriov"
37
38
39 def get_short_key_uuid(uuid):
40     return str(uuid)[:HEAT_KEY_UUID_LENGTH]
41
42
43 class HeatObject(object):
44     """base class for template and stack"""
45
46     def __init__(self):
47         self._heat_client = None
48         self.uuid = None
49
50     def _get_heat_client(self):
51         """returns a heat client instance"""
52
53         if self._heat_client is None:
54             sess = op_utils.get_session()
55             heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
56             self._heat_client = heatclient.client.Client(
57                 op_utils.get_heat_api_version(),
58                 endpoint=heat_endpoint, session=sess)
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.warning(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_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
196                    is_public=True, rxtx_factor=1.0, swap=0,
197                    extra_specs=None):
198         """add to the template a Flavor description"""
199         if name is None:
200             name = 'auto'
201         log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' " +
202                   "ephemeral '%d' is_public '%s' rxtx_factor '%d' " +
203                   "swap '%d' extra_specs '%s' ",
204                   name, vcpus, ram, disk, ephemeral, is_public,
205                   rxtx_factor, swap, str(extra_specs))
206
207         if extra_specs:
208             assert isinstance(extra_specs, collections.Mapping)
209
210         self.resources[name] = {
211             'type': 'OS::Nova::Flavor',
212             'properties': {'name': name,
213                            'disk': disk,
214                            'vcpus': vcpus,
215                            'swap': swap,
216                            'flavorid': name,
217                            'rxtx_factor': rxtx_factor,
218                            'ram': ram,
219                            'is_public': is_public,
220                            'ephemeral': ephemeral,
221                            'extra_specs': extra_specs}
222         }
223
224         self._template['outputs'][name] = {
225             'description': 'Flavor %s ID' % name,
226             'value': {'get_resource': name}
227         }
228
229     def add_network(self, name, physical_network='physnet1', provider=None):
230         """add to the template a Neutron Net"""
231         log.debug("adding Neutron::Net '%s'", name)
232         if provider is None:
233             self.resources[name] = {
234                 'type': 'OS::Neutron::Net',
235                 'properties': {'name': name}
236             }
237         else:
238             self.resources[name] = {
239                 'type': 'OS::Neutron::ProviderNet',
240                 'properties': {
241                     'name': name,
242                     'network_type': 'vlan',
243                     'physical_network': physical_network
244                 }
245             }
246
247     def add_server_group(self, name, policies):     # pragma: no cover
248         """add to the template a ServerGroup"""
249         log.debug("adding Nova::ServerGroup '%s'", name)
250         policies = policies if isinstance(policies, list) else [policies]
251         self.resources[name] = {
252             'type': 'OS::Nova::ServerGroup',
253             'properties': {'name': name,
254                            'policies': policies}
255         }
256
257     def add_subnet(self, name, network, cidr):
258         """add to the template a Neutron Subnet"""
259         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
260                   name, network, cidr)
261         self.resources[name] = {
262             'type': 'OS::Neutron::Subnet',
263             'depends_on': network,
264             'properties': {
265                 'name': name,
266                 'cidr': cidr,
267                 'network_id': {'get_resource': network}
268             }
269         }
270
271         self._template['outputs'][name] = {
272             'description': 'subnet %s ID' % name,
273             'value': {'get_resource': name}
274         }
275
276     def add_router(self, name, ext_gw_net, subnet_name):
277         """add to the template a Neutron Router and interface"""
278         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
279         self.resources[name] = {
280             'type': 'OS::Neutron::Router',
281             'depends_on': [subnet_name],
282             'properties': {
283                 'name': name,
284                 'external_gateway_info': {
285                     'network': ext_gw_net
286                 }
287             }
288         }
289
290     def add_router_interface(self, name, router_name, subnet_name):
291         """add to the template a Neutron RouterInterface and interface"""
292         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
293                   "subnet:'%s'", name, router_name, subnet_name)
294         self.resources[name] = {
295             'type': 'OS::Neutron::RouterInterface',
296             'depends_on': [router_name, subnet_name],
297             'properties': {
298                 'router_id': {'get_resource': router_name},
299                 'subnet_id': {'get_resource': subnet_name}
300             }
301         }
302
303     def add_port(self, name, network_name, subnet_name, sec_group_id=None,
304                  provider=None):
305         """add to the template a named Neutron Port"""
306         log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
307                   "secgroup:%s", name, network_name, subnet_name, sec_group_id)
308         self.resources[name] = {
309             'type': 'OS::Neutron::Port',
310             'depends_on': [subnet_name],
311             'properties': {
312                 'name': name,
313                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
314                 'network_id': {'get_resource': network_name},
315                 'replacement_policy': 'AUTO',
316             }
317         }
318
319         if provider == PROVIDER_SRIOV:
320             self.resources[name]['properties']['binding:vnic_type'] = \
321                 'direct'
322
323         if sec_group_id:
324             self.resources[name]['depends_on'].append(sec_group_id)
325             self.resources[name]['properties']['security_groups'] = \
326                 [sec_group_id]
327
328         self._template['outputs'][name] = {
329             'description': 'Address for interface %s' % name,
330             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
331         }
332
333     def add_floating_ip(self, name, network_name, port_name, router_if_name,
334                         secgroup_name=None):
335         """add to the template a Nova FloatingIP resource
336         see: https://bugs.launchpad.net/heat/+bug/1299259
337         """
338         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
339                   "rif '%s'", name, network_name, port_name, router_if_name)
340
341         self.resources[name] = {
342             'type': 'OS::Nova::FloatingIP',
343             'depends_on': [port_name, router_if_name],
344             'properties': {
345                 'pool': network_name
346             }
347         }
348
349         if secgroup_name:
350             self.resources[name]["depends_on"].append(secgroup_name)
351
352         self._template['outputs'][name] = {
353             'description': 'floating ip %s' % name,
354             'value': {'get_attr': [name, 'ip']}
355         }
356
357     def add_floating_ip_association(self, name, floating_ip_name, port_name):
358         """add to the template a Nova FloatingIP Association resource
359         """
360         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
361                   "floating_ip '%s'", name, port_name, floating_ip_name)
362
363         self.resources[name] = {
364             'type': 'OS::Neutron::FloatingIPAssociation',
365             'depends_on': [port_name],
366             'properties': {
367                 'floatingip_id': {'get_resource': floating_ip_name},
368                 'port_id': {'get_resource': port_name}
369             }
370         }
371
372     def add_keypair(self, name, key_uuid):
373         """add to the template a Nova KeyPair"""
374         log.debug("adding Nova::KeyPair '%s'", name)
375         self.resources[name] = {
376             'type': 'OS::Nova::KeyPair',
377             'properties': {
378                 'name': name,
379                 # resource_string returns bytes, so we must decode to unicode
380                 'public_key': encodeutils.safe_decode(
381                     pkg_resources.resource_string(
382                         'yardstick.resources',
383                         'files/yardstick_key-' +
384                         get_short_key_uuid(key_uuid) + '.pub'),
385                     'utf-8')
386             }
387         }
388
389     def add_servergroup(self, name, policy):
390         """add to the template a Nova ServerGroup"""
391         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
392         if policy not in ["anti-affinity", "affinity"]:
393             raise ValueError(policy)
394
395         self.resources[name] = {
396             'type': 'OS::Nova::ServerGroup',
397             'properties': {
398                 'name': name,
399                 'policies': [policy]
400             }
401         }
402
403         self._template['outputs'][name] = {
404             'description': 'ID Server Group %s' % name,
405             'value': {'get_resource': name}
406         }
407
408     def add_security_group(self, name):
409         """add to the template a Neutron SecurityGroup"""
410         log.debug("adding Neutron::SecurityGroup '%s'", name)
411         self.resources[name] = {
412             'type': 'OS::Neutron::SecurityGroup',
413             'properties': {
414                 'name': name,
415                 'description': "Group allowing icmp and upd/tcp on all ports",
416                 'rules': [
417                     {'remote_ip_prefix': '0.0.0.0/0',
418                      'protocol': 'tcp',
419                      'port_range_min': '1',
420                      'port_range_max': '65535'},
421                     {'remote_ip_prefix': '0.0.0.0/0',
422                      'protocol': 'udp',
423                      'port_range_min': '1',
424                      'port_range_max': '65535'},
425                     {'remote_ip_prefix': '0.0.0.0/0',
426                      'protocol': 'icmp'}
427                 ]
428             }
429         }
430
431         self._template['outputs'][name] = {
432             'description': 'ID of Security Group',
433             'value': {'get_resource': name}
434         }
435
436     def add_server(self, name, image, flavor, flavors, ports=None,
437                    networks=None, scheduler_hints=None, user=None,
438                    key_name=None, user_data=None, metadata=None,
439                    additional_properties=None):
440         """add to the template a Nova Server"""
441         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
442                   "ports %s", name, image, flavor, ports)
443
444         self.resources[name] = {
445             'type': 'OS::Nova::Server',
446             'depends_on': []
447         }
448
449         server_properties = {
450             'name': name,
451             'image': image,
452             'flavor': {},
453             'networks': []  # list of dictionaries
454         }
455
456         if flavor in flavors:
457             self.resources[name]['depends_on'].append(flavor)
458             server_properties["flavor"] = {'get_resource': flavor}
459         else:
460             server_properties["flavor"] = flavor
461
462         if user:
463             server_properties['admin_user'] = user
464
465         if key_name:
466             self.resources[name]['depends_on'].append(key_name)
467             server_properties['key_name'] = {'get_resource': key_name}
468
469         if ports:
470             self.resources[name]['depends_on'].extend(ports)
471             for port in ports:
472                 server_properties['networks'].append(
473                     {'port': {'get_resource': port}}
474                 )
475
476         if networks:
477             for i, _ in enumerate(networks):
478                 server_properties['networks'].append({'network': networks[i]})
479
480         if scheduler_hints:
481             server_properties['scheduler_hints'] = scheduler_hints
482
483         if user_data:
484             server_properties['user_data'] = user_data
485
486         if metadata:
487             assert isinstance(metadata, collections.Mapping)
488             server_properties['metadata'] = metadata
489
490         if additional_properties:
491             assert isinstance(additional_properties, collections.Mapping)
492             for prop in additional_properties:
493                 server_properties[prop] = additional_properties[prop]
494
495         server_properties['config_drive'] = True
496
497         self.resources[name]['properties'] = server_properties
498
499         self._template['outputs'][name] = {
500             'description': 'VM UUID',
501             'value': {'get_resource': name}
502         }
503
504     def create(self, block=True):
505         """creates a template in the target cloud using heat
506         returns a dict with the requested output values from the template
507         """
508         log.info("Creating stack '%s'", self.name)
509
510         # create stack early to support cleanup, e.g. ctrl-c while waiting
511         stack = HeatStack(self.name)
512
513         heat = self._get_heat_client()
514         start_time = time.time()
515         stack.uuid = self.uuid = heat.stacks.create(
516             stack_name=self.name, template=self._template,
517             parameters=self.heat_parameters)['stack']['id']
518
519         status = self.status()
520         outputs = []
521
522         if block:
523             while status != u'CREATE_COMPLETE':
524                 log.debug("stack state %s", status)
525                 if status == u'CREATE_FAILED':
526                     raise RuntimeError(getattr(heat.stacks.get(self.uuid),
527                                                'stack_status_reason'))
528
529                 time.sleep(2)
530                 status = self.status()
531
532             end_time = time.time()
533             outputs = getattr(heat.stacks.get(self.uuid), 'outputs')
534             log.info("Created stack '%s' in %d secs",
535                      self.name, end_time - start_time)
536
537         # keep outputs as unicode
538         self.outputs = {output["output_key"]: output["output_value"] for output
539                         in outputs}
540
541         stack.outputs = self.outputs
542         return stack