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