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