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