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