Merge "Fix RabbitMQ service installation and initialization"
[yardstick.git] / yardstick / orchestrator / heat.py
1 #############################################################################
2 # Copyright (c) 2015-2017 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 import collections
14 import datetime
15 import getpass
16 import logging
17 import pkg_resources
18 import pprint
19 import socket
20 import tempfile
21 import time
22
23 from oslo_serialization import jsonutils
24 from oslo_utils import encodeutils
25 import shade
26 from shade._heat import event_utils
27
28 import yardstick.common.openstack_utils as op_utils
29 from yardstick.common import exceptions
30 from yardstick.common import template_format
31 from yardstick.common import constants as consts
32
33 log = logging.getLogger(__name__)
34
35
36 PROVIDER_SRIOV = "sriov"
37
38 _DEPLOYED_STACKS = {}
39
40
41 class HeatStack(object):
42     """Represents a Heat stack (deployed template) """
43
44     def __init__(self, name):
45         self.name = name
46         self.outputs = {}
47         self._cloud = shade.openstack_cloud()
48         self._stack = None
49
50     def _update_stack_tracking(self):
51         outputs = self._stack.outputs
52         self.outputs = {output['output_key']: output['output_value'] for output
53                         in outputs}
54         if self.uuid:
55             _DEPLOYED_STACKS[self.uuid] = self._stack
56
57     def create(self, template, heat_parameters, wait, timeout):
58         """Creates an OpenStack stack from a template"""
59         with tempfile.NamedTemporaryFile('wb', delete=False) as template_file:
60             template_file.write(jsonutils.dump_as_bytes(template))
61             template_file.close()
62             self._stack = self._cloud.create_stack(
63                 self.name, template_file=template_file.name, wait=wait,
64                 timeout=timeout, **heat_parameters)
65
66         self._update_stack_tracking()
67
68     def get_failures(self):
69         return event_utils.get_events(self._cloud, self._stack.id,
70                                       event_args={'resource_status': 'FAILED'})
71
72     def get(self):
73         """Retrieves an existing stack from the target cloud
74
75         Returns a bool indicating whether the stack exists in the target cloud
76         If the stack exists, it will be stored as self._stack
77         """
78         self._stack = self._cloud.get_stack(self.name)
79         if not self._stack:
80             return False
81
82         self._update_stack_tracking()
83         return True
84
85     @staticmethod
86     def stacks_exist():
87         """Check if any stack has been deployed"""
88         return len(_DEPLOYED_STACKS) > 0
89
90     def delete(self, wait=True):
91         """Deletes a stack in the target cloud"""
92         if self.uuid is None:
93             return
94
95         try:
96             ret = self._cloud.delete_stack(self.uuid, wait=wait)
97         except TypeError:
98             # NOTE(ralonsoh): this exception catch solves a bug in Shade, which
99             # tries to retrieve and read the stack status when it's already
100             # deleted.
101             ret = True
102
103         _DEPLOYED_STACKS.pop(self.uuid)
104         self._stack = None
105         return ret
106
107     @staticmethod
108     def delete_all():
109         """Delete all deployed stacks"""
110         for stack in _DEPLOYED_STACKS:
111             stack.delete()
112
113     @property
114     def status(self):
115         """Retrieve the current stack status"""
116         if self._stack:
117             return self._stack.status
118
119     @property
120     def uuid(self):
121         """Retrieve the current stack ID"""
122         if self._stack:
123             return self._stack.id
124
125
126 class HeatTemplate(object):
127     """Describes a Heat template and a method to deploy template to a stack"""
128
129     DESCRIPTION_TEMPLATE = """
130 Stack built by the yardstick framework for %s on host %s %s.
131 All referred generated resources are prefixed with the template
132 name (i.e. %s).
133 """
134
135     HEAT_WAIT_LOOP_INTERVAL = 2
136     HEAT_STATUS_COMPLETE = 'COMPLETE'
137
138     def _init_template(self):
139         timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
140         self._template = {
141             'heat_template_version': '2013-05-23',
142             'description': self.DESCRIPTION_TEMPLATE % (
143                 getpass.getuser(),
144                 socket.gethostname(),
145                 timestamp,
146                 self.name
147             ),
148             'resources': {},
149             'outputs': {}
150         }
151
152         # short hand for resources part of template
153         self.resources = self._template['resources']
154
155     def __init__(self, name, template_file=None, heat_parameters=None):
156         self.name = name
157         self.keystone_client = None
158         self.heat_parameters = {}
159
160         # heat_parameters is passed to heat in stack create, empty dict when
161         # yardstick creates the template (no get_param in resources part)
162         if heat_parameters:
163             self.heat_parameters = heat_parameters
164
165         if template_file:
166             with open(template_file) as stream:
167                 log.info('Parsing external template: %s', template_file)
168                 template_str = stream.read()
169             self._template = template_format.parse(template_str)
170             self._parameters = heat_parameters
171         else:
172             self._init_template()
173
174         log.debug("template object '%s' created", name)
175
176     def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
177                    is_public=True, rxtx_factor=1.0, swap=0,
178                    extra_specs=None):
179         """add to the template a Flavor description"""
180         if name is None:
181             name = 'auto'
182         log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' "
183                   "ephemeral '%d' is_public '%s' rxtx_factor '%d' "
184                   "swap '%d' extra_specs '%s'",
185                   name, vcpus, ram, disk, ephemeral, is_public,
186                   rxtx_factor, swap, str(extra_specs))
187
188         if extra_specs:
189             assert isinstance(extra_specs, collections.Mapping)
190
191         self.resources[name] = {
192             'type': 'OS::Nova::Flavor',
193             'properties': {'name': name,
194                            'disk': disk,
195                            'vcpus': vcpus,
196                            'swap': swap,
197                            'flavorid': name,
198                            'rxtx_factor': rxtx_factor,
199                            'ram': ram,
200                            'is_public': is_public,
201                            'ephemeral': ephemeral,
202                            'extra_specs': extra_specs}
203         }
204
205         self._template['outputs'][name] = {
206             'description': 'Flavor %s ID' % name,
207             'value': {'get_resource': name}
208         }
209
210     def add_volume(self, name, size=10):
211         """add to the template a volume description"""
212         log.debug("adding Cinder::Volume '%s' size '%d' ", name, size)
213
214         self.resources[name] = {
215             'type': 'OS::Cinder::Volume',
216             'properties': {'name': name,
217                            'size': size}
218         }
219
220         self._template['outputs'][name] = {
221             'description': 'Volume %s ID' % name,
222             'value': {'get_resource': name}
223         }
224
225     def add_volume_attachment(self, server_name, volume_name, mountpoint=None):
226         """add to the template an association of volume to instance"""
227         log.debug("adding Cinder::VolumeAttachment server '%s' volume '%s' ", server_name,
228                   volume_name)
229
230         name = "%s-%s" % (server_name, volume_name)
231
232         volume_id = op_utils.get_volume_id(volume_name)
233         if not volume_id:
234             volume_id = {'get_resource': volume_name}
235         self.resources[name] = {
236             'type': 'OS::Cinder::VolumeAttachment',
237             'properties': {'instance_uuid': {'get_resource': server_name},
238                            'volume_id': volume_id}
239         }
240
241         if mountpoint:
242             self.resources[name]['properties']['mountpoint'] = mountpoint
243
244     def add_network(self, name, physical_network='physnet1', provider=None,
245                     segmentation_id=None, port_security_enabled=None, network_type=None):
246         """add to the template a Neutron Net"""
247         log.debug("adding Neutron::Net '%s'", name)
248         if provider is None:
249             self.resources[name] = {
250                 'type': 'OS::Neutron::Net',
251                 'properties': {
252                     'name': name,
253                 }
254             }
255         else:
256             self.resources[name] = {
257                 'type': 'OS::Neutron::ProviderNet',
258                 'properties': {
259                     'name': name,
260                     'network_type': 'flat' if network_type is None else network_type,
261                     'physical_network': physical_network,
262                 },
263             }
264             if segmentation_id:
265                 self.resources[name]['properties']['segmentation_id'] = segmentation_id
266                 if network_type is None:
267                     self.resources[name]['properties']['network_type'] = 'vlan'
268         # if port security is not defined then don't add to template:
269         # some deployments don't have port security plugin installed
270         if port_security_enabled is not None:
271             self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
272
273     def add_server_group(self, name, policies):     # pragma: no cover
274         """add to the template a ServerGroup"""
275         log.debug("adding Nova::ServerGroup '%s'", name)
276         policies = policies if isinstance(policies, list) else [policies]
277         self.resources[name] = {
278             'type': 'OS::Nova::ServerGroup',
279             'properties': {'name': name,
280                            'policies': policies}
281         }
282
283     def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
284         """add to the template a Neutron Subnet
285         """
286         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
287                   name, network, cidr)
288         self.resources[name] = {
289             'type': 'OS::Neutron::Subnet',
290             'depends_on': network,
291             'properties': {
292                 'name': name,
293                 'cidr': cidr,
294                 'network_id': {'get_resource': network},
295                 'enable_dhcp': enable_dhcp,
296             }
297         }
298         if gateway_ip == 'null':
299             self.resources[name]['properties']['gateway_ip'] = None
300         elif gateway_ip is not None:
301             self.resources[name]['properties']['gateway_ip'] = gateway_ip
302
303         self._template['outputs'][name] = {
304             'description': 'subnet %s ID' % name,
305             'value': {'get_resource': name}
306         }
307         self._template['outputs'][name + "-cidr"] = {
308             'description': 'subnet %s cidr' % name,
309             'value': {'get_attr': [name, 'cidr']}
310         }
311         self._template['outputs'][name + "-gateway_ip"] = {
312             'description': 'subnet %s gateway_ip' % name,
313             'value': {'get_attr': [name, 'gateway_ip']}
314         }
315
316     def add_router(self, name, ext_gw_net, subnet_name):
317         """add to the template a Neutron Router and interface"""
318         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
319         self.resources[name] = {
320             'type': 'OS::Neutron::Router',
321             'depends_on': [subnet_name],
322             'properties': {
323                 'name': name,
324                 'external_gateway_info': {
325                     'network': ext_gw_net
326                 }
327             }
328         }
329
330     def add_router_interface(self, name, router_name, subnet_name):
331         """add to the template a Neutron RouterInterface and interface"""
332         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
333                   "subnet:'%s'", name, router_name, subnet_name)
334         self.resources[name] = {
335             'type': 'OS::Neutron::RouterInterface',
336             'depends_on': [router_name, subnet_name],
337             'properties': {
338                 'router_id': {'get_resource': router_name},
339                 'subnet_id': {'get_resource': subnet_name}
340             }
341         }
342
343     def add_port(self, name, network, sec_group_id=None,
344                  provider=None, allowed_address_pairs=None):
345         """add to the template a named Neutron Port
346         """
347         net_is_existing = network.net_flags.get(consts.IS_EXISTING)
348         depends_on = [] if net_is_existing else [network.subnet_stack_name]
349         fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
350             {'subnet': {'get_resource': network.subnet_stack_name}}]
351         network_ = network.name if net_is_existing else {
352             'get_resource': network.stack_name}
353         self.resources[name] = {
354             'type': 'OS::Neutron::Port',
355             'depends_on': depends_on,
356             'properties': {
357                 'name': name,
358                 'binding:vnic_type': network.vnic_type,
359                 'fixed_ips': fixed_ips,
360                 'network': network_,
361             }
362         }
363
364         if provider == PROVIDER_SRIOV:
365             self.resources[name]['properties']['binding:vnic_type'] = \
366                 'direct'
367
368         if sec_group_id:
369             self.resources[name]['depends_on'].append(sec_group_id)
370             self.resources[name]['properties']['security_groups'] = \
371                 [sec_group_id]
372
373         if allowed_address_pairs:
374             self.resources[name]['properties'][
375                 'allowed_address_pairs'] = allowed_address_pairs
376
377         log.debug("adding Neutron::Port %s", self.resources[name])
378
379         self._template['outputs'][name] = {
380             'description': 'Address for interface %s' % name,
381             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
382         }
383         self._template['outputs'][name + "-subnet_id"] = {
384             'description': 'Address for interface %s' % name,
385             'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
386         }
387         self._template['outputs'][name + "-mac_address"] = {
388             'description': 'MAC Address for interface %s' % name,
389             'value': {'get_attr': [name, 'mac_address']}
390         }
391         self._template['outputs'][name + "-device_id"] = {
392             'description': 'Device ID for interface %s' % name,
393             'value': {'get_attr': [name, 'device_id']}
394         }
395         self._template['outputs'][name + "-network_id"] = {
396             'description': 'Network ID for interface %s' % name,
397             'value': {'get_attr': [name, 'network_id']}
398         }
399
400     def add_floating_ip(self, name, network_name, port_name, router_if_name,
401                         secgroup_name=None):
402         """add to the template a Nova FloatingIP resource
403         see: https://bugs.launchpad.net/heat/+bug/1299259
404         """
405         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
406                   "rif '%s'", name, network_name, port_name, router_if_name)
407
408         self.resources[name] = {
409             'type': 'OS::Nova::FloatingIP',
410             'depends_on': [port_name, router_if_name],
411             'properties': {
412                 'pool': network_name
413             }
414         }
415
416         if secgroup_name:
417             self.resources[name]["depends_on"].append(secgroup_name)
418
419         self._template['outputs'][name] = {
420             'description': 'floating ip %s' % name,
421             'value': {'get_attr': [name, 'ip']}
422         }
423
424     def add_floating_ip_association(self, name, floating_ip_name, port_name):
425         """add to the template a Nova FloatingIP Association resource
426         """
427         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
428                   "floating_ip '%s'", name, port_name, floating_ip_name)
429
430         self.resources[name] = {
431             'type': 'OS::Neutron::FloatingIPAssociation',
432             'depends_on': [port_name],
433             'properties': {
434                 'floatingip_id': {'get_resource': floating_ip_name},
435                 'port_id': {'get_resource': port_name}
436             }
437         }
438
439     def add_keypair(self, name, key_id):
440         """add to the template a Nova KeyPair"""
441         log.debug("adding Nova::KeyPair '%s'", name)
442         self.resources[name] = {
443             'type': 'OS::Nova::KeyPair',
444             'properties': {
445                 'name': name,
446                 # resource_string returns bytes, so we must decode to unicode
447                 'public_key': encodeutils.safe_decode(
448                     pkg_resources.resource_string(
449                         'yardstick.resources',
450                         'files/yardstick_key-' +
451                         key_id + '.pub'),
452                     'utf-8')
453             }
454         }
455
456     def add_servergroup(self, name, policy):
457         """add to the template a Nova ServerGroup"""
458         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
459         if policy not in ["anti-affinity", "affinity"]:
460             raise ValueError(policy)
461
462         self.resources[name] = {
463             'type': 'OS::Nova::ServerGroup',
464             'properties': {
465                 'name': name,
466                 'policies': [policy]
467             }
468         }
469
470         self._template['outputs'][name] = {
471             'description': 'ID Server Group %s' % name,
472             'value': {'get_resource': name}
473         }
474
475     def add_security_group(self, name):
476         """add to the template a Neutron SecurityGroup"""
477         log.debug("adding Neutron::SecurityGroup '%s'", name)
478         self.resources[name] = {
479             'type': 'OS::Neutron::SecurityGroup',
480             'properties': {
481                 'name': name,
482                 'description': "Group allowing IPv4 and IPv6 for icmp and upd/tcp on all ports",
483                 'rules': [
484                     {'remote_ip_prefix': '0.0.0.0/0',
485                      'protocol': 'tcp',
486                      'port_range_min': '1',
487                      'port_range_max': '65535'},
488                     {'remote_ip_prefix': '0.0.0.0/0',
489                      'protocol': 'udp',
490                      'port_range_min': '1',
491                      'port_range_max': '65535'},
492                     {'remote_ip_prefix': '0.0.0.0/0',
493                      'protocol': 'icmp'},
494                     {'remote_ip_prefix': '::/0',
495                      'ethertype': 'IPv6',
496                      'protocol': 'tcp',
497                      'port_range_min': '1',
498                      'port_range_max': '65535'},
499                     {'remote_ip_prefix': '::/0',
500                      'ethertype': 'IPv6',
501                      'protocol': 'udp',
502                      'port_range_min': '1',
503                      'port_range_max': '65535'},
504                     {'remote_ip_prefix': '::/0',
505                      'ethertype': 'IPv6',
506                      'protocol': 'ipv6-icmp'},
507                     {'remote_ip_prefix': '0.0.0.0/0',
508                      'direction': 'egress',
509                      'protocol': 'tcp',
510                      'port_range_min': '1',
511                      'port_range_max': '65535'},
512                     {'remote_ip_prefix': '0.0.0.0/0',
513                      'direction': 'egress',
514                      'protocol': 'udp',
515                      'port_range_min': '1',
516                      'port_range_max': '65535'},
517                     {'remote_ip_prefix': '0.0.0.0/0',
518                      'direction': 'egress',
519                      'protocol': 'icmp'},
520                     {'remote_ip_prefix': '::/0',
521                      'direction': 'egress',
522                      'ethertype': 'IPv6',
523                      'protocol': 'tcp',
524                      'port_range_min': '1',
525                      'port_range_max': '65535'},
526                     {'remote_ip_prefix': '::/0',
527                      'direction': 'egress',
528                      'ethertype': 'IPv6',
529                      'protocol': 'udp',
530                      'port_range_min': '1',
531                      'port_range_max': '65535'},
532                     {'remote_ip_prefix': '::/0',
533                      'direction': 'egress',
534                      'ethertype': 'IPv6',
535                      'protocol': 'ipv6-icmp'},
536                 ]
537             }
538         }
539
540         self._template['outputs'][name] = {
541             'description': 'ID of Security Group',
542             'value': {'get_resource': name}
543         }
544
545     def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
546                    scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
547                    additional_properties=None, availability_zone=None):
548         """add to the template a Nova Server """
549         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
550                   "ports %s", name, image, flavor, ports)
551
552         self.resources[name] = {
553             'type': 'OS::Nova::Server',
554             'depends_on': []
555         }
556
557         server_properties = {
558             'name': name,
559             'image': image,
560             'flavor': {},
561             'networks': []  # list of dictionaries
562         }
563         if availability_zone:
564             server_properties["availability_zone"] = availability_zone
565
566         if flavor in flavors:
567             self.resources[name]['depends_on'].append(flavor)
568             server_properties["flavor"] = {'get_resource': flavor}
569         else:
570             server_properties["flavor"] = flavor
571
572         if user:
573             server_properties['admin_user'] = user
574
575         if key_name:
576             self.resources[name]['depends_on'].append(key_name)
577             server_properties['key_name'] = {'get_resource': key_name}
578
579         if ports:
580             self.resources[name]['depends_on'].extend(ports)
581             for port in ports:
582                 server_properties['networks'].append(
583                     {'port': {'get_resource': port}}
584                 )
585
586         if networks:
587             for i, _ in enumerate(networks):
588                 server_properties['networks'].append({'network': networks[i]})
589
590         if scheduler_hints:
591             server_properties['scheduler_hints'] = scheduler_hints
592
593         if user_data:
594             server_properties['user_data'] = user_data
595
596         if metadata:
597             assert isinstance(metadata, collections.Mapping)
598             server_properties['metadata'] = metadata
599
600         if additional_properties:
601             assert isinstance(additional_properties, collections.Mapping)
602             for prop in additional_properties:
603                 server_properties[prop] = additional_properties[prop]
604
605         server_properties['config_drive'] = True
606
607         self.resources[name]['properties'] = server_properties
608
609         self._template['outputs'][name] = {
610             'description': 'VM UUID',
611             'value': {'get_resource': name}
612         }
613
614     def create(self, block=True, timeout=3600):
615         """Creates a stack in the target based on the stored template
616
617         :param block: (bool) Wait for Heat create to finish
618         :param timeout: (int) Timeout in seconds for Heat create,
619                default 3600s
620         :return A dict with the requested output values from the template
621         """
622         log.info("Creating stack '%s' START", self.name)
623
624         start_time = time.time()
625         stack = HeatStack(self.name)
626         stack.create(self._template, self.heat_parameters, block, timeout)
627
628         if not block:
629             log.info("Creating stack '%s' DONE in %d secs",
630                      self.name, time.time() - start_time)
631             return stack
632
633         if stack.status != self.HEAT_STATUS_COMPLETE:
634             for event in stack.get_failures():
635                 log.error("%s", event.resource_status_reason)
636             log.error(pprint.pformat(self._template))
637             raise exceptions.HeatTemplateError(stack_name=self.name)
638
639         log.info("Creating stack '%s' DONE in %d secs",
640                  self.name, time.time() - start_time)
641         return stack