Make security group configurable - dovetail
[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         # TODO(elfoley): Fix this on master, it is a bug, and exposes untested
236         # code.  Yardstick will crash when heat context uses volume.
237         # pylint: disable=no-value-for-parameter
238         volume_id = op_utils.get_volume_id(volume_name)
239         # pylint: enable=no-value-for-parameter
240         if not volume_id:
241             volume_id = {'get_resource': volume_name}
242         self.resources[name] = {
243             'type': 'OS::Cinder::VolumeAttachment',
244             'properties': {'instance_uuid': {'get_resource': server_name},
245                            'volume_id': volume_id}
246         }
247
248         if mountpoint:
249             self.resources[name]['properties']['mountpoint'] = mountpoint
250
251     def add_network(self, name, physical_network='physnet1', provider=None,
252                     segmentation_id=None, port_security_enabled=None, network_type=None):
253         """add to the template a Neutron Net"""
254         log.debug("adding Neutron::Net '%s'", name)
255         if provider is None:
256             self.resources[name] = {
257                 'type': 'OS::Neutron::Net',
258                 'properties': {
259                     'name': name,
260                 }
261             }
262         else:
263             self.resources[name] = {
264                 'type': 'OS::Neutron::ProviderNet',
265                 'properties': {
266                     'name': name,
267                     'network_type': 'flat' if network_type is None else network_type,
268                     'physical_network': physical_network,
269                 },
270             }
271             if segmentation_id:
272                 self.resources[name]['properties']['segmentation_id'] = segmentation_id
273                 if network_type is None:
274                     self.resources[name]['properties']['network_type'] = 'vlan'
275         # if port security is not defined then don't add to template:
276         # some deployments don't have port security plugin installed
277         if port_security_enabled is not None:
278             self.resources[name]['properties']['port_security_enabled'] = port_security_enabled
279
280     def add_server_group(self, name, policies):     # pragma: no cover
281         """add to the template a ServerGroup"""
282         log.debug("adding Nova::ServerGroup '%s'", name)
283         policies = policies if isinstance(policies, list) else [policies]
284         self.resources[name] = {
285             'type': 'OS::Nova::ServerGroup',
286             'properties': {'name': name,
287                            'policies': policies}
288         }
289
290     def add_subnet(self, name, network, cidr, enable_dhcp='true', gateway_ip=None):
291         """add to the template a Neutron Subnet
292         """
293         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
294                   name, network, cidr)
295         self.resources[name] = {
296             'type': 'OS::Neutron::Subnet',
297             'depends_on': network,
298             'properties': {
299                 'name': name,
300                 'cidr': cidr,
301                 'network_id': {'get_resource': network},
302                 'enable_dhcp': enable_dhcp,
303             }
304         }
305         if gateway_ip == 'null':
306             self.resources[name]['properties']['gateway_ip'] = None
307         elif gateway_ip is not None:
308             self.resources[name]['properties']['gateway_ip'] = gateway_ip
309
310         self._template['outputs'][name] = {
311             'description': 'subnet %s ID' % name,
312             'value': {'get_resource': name}
313         }
314         self._template['outputs'][name + "-cidr"] = {
315             'description': 'subnet %s cidr' % name,
316             'value': {'get_attr': [name, 'cidr']}
317         }
318         self._template['outputs'][name + "-gateway_ip"] = {
319             'description': 'subnet %s gateway_ip' % name,
320             'value': {'get_attr': [name, 'gateway_ip']}
321         }
322
323     def add_router(self, name, ext_gw_net, subnet_name):
324         """add to the template a Neutron Router and interface"""
325         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
326         self.resources[name] = {
327             'type': 'OS::Neutron::Router',
328             'depends_on': [subnet_name],
329             'properties': {
330                 'name': name,
331                 'external_gateway_info': {
332                     'network': ext_gw_net
333                 }
334             }
335         }
336
337     def add_router_interface(self, name, router_name, subnet_name):
338         """add to the template a Neutron RouterInterface and interface"""
339         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
340                   "subnet:'%s'", name, router_name, subnet_name)
341         self.resources[name] = {
342             'type': 'OS::Neutron::RouterInterface',
343             'depends_on': [router_name, subnet_name],
344             'properties': {
345                 'router_id': {'get_resource': router_name},
346                 'subnet_id': {'get_resource': subnet_name}
347             }
348         }
349
350     def add_port(self, name, network, sec_group_id=None,
351                  provider=None, allowed_address_pairs=None):
352         """add to the template a named Neutron Port
353         """
354         net_is_existing = network.net_flags.get(consts.IS_EXISTING)
355         depends_on = [] if net_is_existing else [network.subnet_stack_name]
356         fixed_ips = [{'subnet': network.subnet}] if net_is_existing else [
357             {'subnet': {'get_resource': network.subnet_stack_name}}]
358         network_ = network.name if net_is_existing else {
359             'get_resource': network.stack_name}
360         self.resources[name] = {
361             'type': 'OS::Neutron::Port',
362             'depends_on': depends_on,
363             'properties': {
364                 'name': name,
365                 'binding:vnic_type': network.vnic_type,
366                 'fixed_ips': fixed_ips,
367                 'network': network_,
368             }
369         }
370
371         if provider == PROVIDER_SRIOV:
372             self.resources[name]['properties']['binding:vnic_type'] = \
373                 'direct'
374
375         if sec_group_id:
376             self.resources[name]['depends_on'].append(sec_group_id)
377             self.resources[name]['properties']['security_groups'] = \
378                 [sec_group_id]
379
380         if allowed_address_pairs:
381             self.resources[name]['properties'][
382                 'allowed_address_pairs'] = allowed_address_pairs
383
384         log.debug("adding Neutron::Port %s", self.resources[name])
385
386         self._template['outputs'][name] = {
387             'description': 'Address for interface %s' % name,
388             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
389         }
390         self._template['outputs'][name + "-subnet_id"] = {
391             'description': 'Address for interface %s' % name,
392             'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
393         }
394         self._template['outputs'][name + "-mac_address"] = {
395             'description': 'MAC Address for interface %s' % name,
396             'value': {'get_attr': [name, 'mac_address']}
397         }
398         self._template['outputs'][name + "-device_id"] = {
399             'description': 'Device ID for interface %s' % name,
400             'value': {'get_attr': [name, 'device_id']}
401         }
402         self._template['outputs'][name + "-network_id"] = {
403             'description': 'Network ID for interface %s' % name,
404             'value': {'get_attr': [name, 'network_id']}
405         }
406
407     def add_floating_ip(self, name, network_name, port_name, router_if_name,
408                         secgroup_name=None):
409         """add to the template a Nova FloatingIP resource
410         see: https://bugs.launchpad.net/heat/+bug/1299259
411         """
412         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
413                   "rif '%s'", name, network_name, port_name, router_if_name)
414
415         self.resources[name] = {
416             'type': 'OS::Nova::FloatingIP',
417             'depends_on': [port_name, router_if_name],
418             'properties': {
419                 'pool': network_name
420             }
421         }
422
423         if secgroup_name:
424             self.resources[name]["depends_on"].append(secgroup_name)
425
426         self._template['outputs'][name] = {
427             'description': 'floating ip %s' % name,
428             'value': {'get_attr': [name, 'ip']}
429         }
430
431     def add_floating_ip_association(self, name, floating_ip_name, port_name):
432         """add to the template a Nova FloatingIP Association resource
433         """
434         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
435                   "floating_ip '%s'", name, port_name, floating_ip_name)
436
437         self.resources[name] = {
438             'type': 'OS::Neutron::FloatingIPAssociation',
439             'depends_on': [port_name],
440             'properties': {
441                 'floatingip_id': {'get_resource': floating_ip_name},
442                 'port_id': {'get_resource': port_name}
443             }
444         }
445
446     def add_keypair(self, name, key_id):
447         """add to the template a Nova KeyPair"""
448         log.debug("adding Nova::KeyPair '%s'", name)
449         self.resources[name] = {
450             'type': 'OS::Nova::KeyPair',
451             'properties': {
452                 'name': name,
453                 # resource_string returns bytes, so we must decode to unicode
454                 'public_key': encodeutils.safe_decode(
455                     pkg_resources.resource_string(
456                         'yardstick.resources',
457                         'files/yardstick_key-' +
458                         key_id + '.pub'),
459                     'utf-8')
460             }
461         }
462
463     def add_servergroup(self, name, policy):
464         """add to the template a Nova ServerGroup"""
465         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
466         if policy not in ["anti-affinity", "affinity"]:
467             raise ValueError(policy)
468
469         self.resources[name] = {
470             'type': 'OS::Nova::ServerGroup',
471             'properties': {
472                 'name': name,
473                 'policies': [policy]
474             }
475         }
476
477         self._template['outputs'][name] = {
478             'description': 'ID Server Group %s' % name,
479             'value': {'get_resource': name}
480         }
481
482     def add_security_group(self, name, security_group=None):
483         """add to the template a Neutron SecurityGroup"""
484         log.debug("adding Neutron::SecurityGroup '%s'", name)
485         description = ("Group allowing IPv4 and IPv6 for icmp and upd/tcp on"
486                        "all ports")
487         rules = [
488             {'remote_ip_prefix': '0.0.0.0/0',
489              'protocol': 'tcp',
490              'port_range_min': '1',
491              'port_range_max': '65535'},
492             {'remote_ip_prefix': '0.0.0.0/0',
493              'protocol': 'udp',
494              'port_range_min': '1',
495              'port_range_max': '65535'},
496             {'remote_ip_prefix': '0.0.0.0/0',
497              'protocol': 'icmp'},
498             {'remote_ip_prefix': '::/0',
499              'ethertype': 'IPv6',
500              'protocol': 'tcp',
501              'port_range_min': '1',
502              'port_range_max': '65535'},
503             {'remote_ip_prefix': '::/0',
504              'ethertype': 'IPv6',
505              'protocol': 'udp',
506              'port_range_min': '1',
507              'port_range_max': '65535'},
508             {'remote_ip_prefix': '::/0',
509              'ethertype': 'IPv6',
510              'protocol': 'ipv6-icmp'},
511             {'remote_ip_prefix': '0.0.0.0/0',
512              'direction': 'egress',
513              'protocol': 'tcp',
514              'port_range_min': '1',
515              'port_range_max': '65535'},
516             {'remote_ip_prefix': '0.0.0.0/0',
517              'direction': 'egress',
518              'protocol': 'udp',
519              'port_range_min': '1',
520              'port_range_max': '65535'},
521             {'remote_ip_prefix': '0.0.0.0/0',
522              'direction': 'egress',
523              'protocol': 'icmp'},
524             {'remote_ip_prefix': '::/0',
525              'direction': 'egress',
526              'ethertype': 'IPv6',
527              'protocol': 'tcp',
528              'port_range_min': '1',
529              'port_range_max': '65535'},
530             {'remote_ip_prefix': '::/0',
531              'direction': 'egress',
532              'ethertype': 'IPv6',
533              'protocol': 'udp',
534              'port_range_min': '1',
535              'port_range_max': '65535'},
536             {'remote_ip_prefix': '::/0',
537              'direction': 'egress',
538              'ethertype': 'IPv6',
539              'protocol': 'ipv6-icmp'},
540         ]
541         if security_group:
542             description = "Custom security group rules defined by the user"
543             rules = security_group.get('rules')
544
545         log.debug("The security group rules is %s", rules)
546
547         self.resources[name] = {
548             'type': 'OS::Neutron::SecurityGroup',
549             'properties': {
550                 'name': name,
551                 'description': description,
552                 'rules': rules
553             }
554         }
555
556         self._template['outputs'][name] = {
557             'description': 'ID of Security Group',
558             'value': {'get_resource': name}
559         }
560
561     def add_server(self, name, image, flavor, flavors, ports=None, networks=None,
562                    scheduler_hints=None, user=None, key_name=None, user_data=None, metadata=None,
563                    additional_properties=None, availability_zone=None):
564         """add to the template a Nova Server """
565         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
566                   "ports %s", name, image, flavor, ports)
567
568         self.resources[name] = {
569             'type': 'OS::Nova::Server',
570             'depends_on': []
571         }
572
573         server_properties = {
574             'name': name,
575             'image': image,
576             'flavor': {},
577             'networks': []  # list of dictionaries
578         }
579         if availability_zone:
580             server_properties["availability_zone"] = availability_zone
581
582         if flavor in flavors:
583             self.resources[name]['depends_on'].append(flavor)
584             server_properties["flavor"] = {'get_resource': flavor}
585         else:
586             server_properties["flavor"] = flavor
587
588         if user:
589             server_properties['admin_user'] = user
590
591         if key_name:
592             self.resources[name]['depends_on'].append(key_name)
593             server_properties['key_name'] = {'get_resource': key_name}
594
595         if ports:
596             self.resources[name]['depends_on'].extend(ports)
597             for port in ports:
598                 server_properties['networks'].append(
599                     {'port': {'get_resource': port}}
600                 )
601
602         if networks:
603             for i, _ in enumerate(networks):
604                 server_properties['networks'].append({'network': networks[i]})
605
606         if scheduler_hints:
607             server_properties['scheduler_hints'] = scheduler_hints
608
609         if user_data:
610             server_properties['user_data'] = user_data
611
612         if metadata:
613             assert isinstance(metadata, collections.Mapping)
614             server_properties['metadata'] = metadata
615
616         if additional_properties:
617             assert isinstance(additional_properties, collections.Mapping)
618             for prop in additional_properties:
619                 server_properties[prop] = additional_properties[prop]
620
621         server_properties['config_drive'] = True
622
623         self.resources[name]['properties'] = server_properties
624
625         self._template['outputs'][name] = {
626             'description': 'VM UUID',
627             'value': {'get_resource': name}
628         }
629
630     def create(self, block=True, timeout=3600):
631         """Creates a stack in the target based on the stored template
632
633         :param block: (bool) Wait for Heat create to finish
634         :param timeout: (int) Timeout in seconds for Heat create,
635                default 3600s
636         :return A dict with the requested output values from the template
637         """
638         log.info("Creating stack '%s' START", self.name)
639
640         start_time = time.time()
641         stack = HeatStack(self.name, os_cloud_config=self._os_cloud_config)
642         stack.create(self._template, self.heat_parameters, block, timeout)
643
644         if not block:
645             log.info("Creating stack '%s' DONE in %d secs",
646                      self.name, time.time() - start_time)
647             return stack
648
649         if stack.status != self.HEAT_STATUS_COMPLETE:
650             for event in stack.get_failures():
651                 log.error("%s", event.resource_status_reason)
652             log.error(pprint.pformat(self._template))
653             raise exceptions.HeatTemplateError(stack_name=self.name)
654
655         log.info("Creating stack '%s' DONE in %d secs",
656                  self.name, time.time() - start_time)
657         return stack