Merge "Improve Yardstick user-guide"
[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 from __future__ import print_function
14 from six.moves import range
15
16 import collections
17 import datetime
18 import getpass
19 import logging
20
21 import socket
22 import time
23
24 import heatclient
25 import pkg_resources
26
27 from oslo_utils import encodeutils
28
29 import yardstick.common.openstack_utils as op_utils
30 from yardstick.common import template_format
31
32 log = logging.getLogger(__name__)
33
34
35 HEAT_KEY_UUID_LENGTH = 8
36
37 PROVIDER_SRIOV = "sriov"
38
39
40 def get_short_key_uuid(uuid):
41     return str(uuid)[:HEAT_KEY_UUID_LENGTH]
42
43
44 class HeatObject(object):
45     """base class for template and stack"""
46
47     def __init__(self):
48         self._heat_client = None
49         self.uuid = None
50
51     @property
52     def heat_client(self):
53         """returns a heat client instance"""
54
55         if self._heat_client is None:
56             sess = op_utils.get_session()
57             heat_endpoint = op_utils.get_endpoint(service_type='orchestration')
58             self._heat_client = heatclient.client.Client(
59                 op_utils.get_heat_api_version(),
60                 endpoint=heat_endpoint, session=sess)
61
62         return self._heat_client
63
64     def status(self):
65         """returns stack state as a string"""
66         heat_client = self.heat_client
67         stack = heat_client.stacks.get(self.uuid)
68         return stack.stack_status
69
70
71 class HeatStack(HeatObject):
72     """Represents a Heat stack (deployed template) """
73     stacks = []
74
75     def __init__(self, name):
76         super(HeatStack, self).__init__()
77         self.uuid = None
78         self.name = name
79         self.outputs = None
80         HeatStack.stacks.append(self)
81
82     @staticmethod
83     def stacks_exist():
84         """check if any stack has been deployed"""
85         return len(HeatStack.stacks) > 0
86
87     def _delete(self):
88         """deletes a stack from the target cloud using heat"""
89         if self.uuid is None:
90             return
91
92         log.info("Deleting stack '%s', uuid:%s", self.name, self.uuid)
93         heat = self.heat_client
94         template = heat.stacks.get(self.uuid)
95         start_time = time.time()
96         template.delete()
97
98         for status in iter(self.status, u'DELETE_COMPLETE'):
99             log.debug("stack state %s", status)
100             if status == u'DELETE_FAILED':
101                 raise RuntimeError(
102                     heat.stacks.get(self.uuid).stack_status_reason)
103
104             time.sleep(2)
105
106         end_time = time.time()
107         log.info("Deleted stack '%s' in %d secs", self.name,
108                  end_time - start_time)
109         self.uuid = None
110
111     def delete(self, block=True, retries=3):
112         """deletes a stack in the target cloud using heat (with retry)
113         Sometimes delete fail with "InternalServerError" and the next attempt
114         succeeds. So it is worthwhile to test a couple of times.
115         """
116         if self.uuid is None:
117             return
118
119         if not block:
120             self._delete()
121             return
122
123         for _ in range(retries):
124             try:
125                 self._delete()
126                 break
127             except RuntimeError as err:
128                 log.warning(err.args)
129                 time.sleep(2)
130
131         # if still not deleted try once more and let it fail everything
132         if self.uuid is not None:
133             self._delete()
134
135         HeatStack.stacks.remove(self)
136
137     @staticmethod
138     def delete_all():
139         for stack in HeatStack.stacks[:]:
140             stack.delete()
141
142     def update(self):
143         """update a stack"""
144         raise RuntimeError("not implemented")
145
146
147 class HeatTemplate(HeatObject):
148     """Describes a Heat template and a method to deploy template to a stack"""
149
150     DESCRIPTION_TEMPLATE = """\
151 Stack built by the yardstick framework for %s on host %s %s.
152 All referred generated resources are prefixed with the template
153 name (i.e. %s).\
154 """
155
156     def _init_template(self):
157         timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
158         self._template = {
159             'heat_template_version': '2013-05-23',
160             'description': self.DESCRIPTION_TEMPLATE % (
161                 getpass.getuser(),
162                 socket.gethostname(),
163                 timestamp,
164                 self.name
165             ),
166             'resources': {},
167             'outputs': {}
168         }
169
170         # short hand for resources part of template
171         self.resources = self._template['resources']
172
173     def __init__(self, name, template_file=None, heat_parameters=None):
174         super(HeatTemplate, self).__init__()
175         self.name = name
176         self.state = "NOT_CREATED"
177         self.keystone_client = None
178         self.heat_parameters = {}
179
180         # heat_parameters is passed to heat in stack create, empty dict when
181         # yardstick creates the template (no get_param in resources part)
182         if heat_parameters:
183             self.heat_parameters = heat_parameters
184
185         if template_file:
186             with open(template_file) as stream:
187                 print("Parsing external template:", template_file)
188                 template_str = stream.read()
189             self._template = template_format.parse(template_str)
190             self._parameters = heat_parameters
191         else:
192             self._init_template()
193
194         # holds results of requested output after deployment
195         self.outputs = {}
196
197         log.debug("template object '%s' created", name)
198
199     def add_flavor(self, name, vcpus=1, ram=1024, disk=1, ephemeral=0,
200                    is_public=True, rxtx_factor=1.0, swap=0,
201                    extra_specs=None):
202         """add to the template a Flavor description"""
203         if name is None:
204             name = 'auto'
205         log.debug("adding Nova::Flavor '%s' vcpus '%d' ram '%d' disk '%d' " +
206                   "ephemeral '%d' is_public '%s' rxtx_factor '%d' " +
207                   "swap '%d' extra_specs '%s' ",
208                   name, vcpus, ram, disk, ephemeral, is_public,
209                   rxtx_factor, swap, str(extra_specs))
210
211         if extra_specs:
212             assert isinstance(extra_specs, collections.Mapping)
213
214         self.resources[name] = {
215             'type': 'OS::Nova::Flavor',
216             'properties': {'name': name,
217                            'disk': disk,
218                            'vcpus': vcpus,
219                            'swap': swap,
220                            'flavorid': name,
221                            'rxtx_factor': rxtx_factor,
222                            'ram': ram,
223                            'is_public': is_public,
224                            'ephemeral': ephemeral,
225                            'extra_specs': extra_specs}
226         }
227
228         self._template['outputs'][name] = {
229             'description': 'Flavor %s ID' % name,
230             'value': {'get_resource': name}
231         }
232
233     def add_network(self, name, physical_network='physnet1', provider=None):
234         """add to the template a Neutron Net"""
235         log.debug("adding Neutron::Net '%s'", name)
236         if provider is None:
237             self.resources[name] = {
238                 'type': 'OS::Neutron::Net',
239                 'properties': {'name': name}
240             }
241         else:
242             self.resources[name] = {
243                 'type': 'OS::Neutron::ProviderNet',
244                 'properties': {
245                     'name': name,
246                     'network_type': 'vlan',
247                     'physical_network': physical_network
248                 }
249             }
250
251     def add_server_group(self, name, policies):     # pragma: no cover
252         """add to the template a ServerGroup"""
253         log.debug("adding Nova::ServerGroup '%s'", name)
254         policies = policies if isinstance(policies, list) else [policies]
255         self.resources[name] = {
256             'type': 'OS::Nova::ServerGroup',
257             'properties': {'name': name,
258                            'policies': policies}
259         }
260
261     def add_subnet(self, name, network, cidr):
262         """add to the template a Neutron Subnet"""
263         log.debug("adding Neutron::Subnet '%s' in network '%s', cidr '%s'",
264                   name, network, cidr)
265         self.resources[name] = {
266             'type': 'OS::Neutron::Subnet',
267             'depends_on': network,
268             'properties': {
269                 'name': name,
270                 'cidr': cidr,
271                 'network_id': {'get_resource': network}
272             }
273         }
274
275         self._template['outputs'][name] = {
276             'description': 'subnet %s ID' % name,
277             'value': {'get_resource': name}
278         }
279         self._template['outputs'][name + "-cidr"] = {
280             'description': 'subnet %s cidr' % name,
281             'value': {'get_attr': [name, 'cidr']}
282         }
283         self._template['outputs'][name + "-gateway_ip"] = {
284             'description': 'subnet %s gateway_ip' % name,
285             'value': {'get_attr': [name, 'gateway_ip']}
286         }
287
288     def add_router(self, name, ext_gw_net, subnet_name):
289         """add to the template a Neutron Router and interface"""
290         log.debug("adding Neutron::Router:'%s', gw-net:'%s'", name, ext_gw_net)
291         self.resources[name] = {
292             'type': 'OS::Neutron::Router',
293             'depends_on': [subnet_name],
294             'properties': {
295                 'name': name,
296                 'external_gateway_info': {
297                     'network': ext_gw_net
298                 }
299             }
300         }
301
302     def add_router_interface(self, name, router_name, subnet_name):
303         """add to the template a Neutron RouterInterface and interface"""
304         log.debug("adding Neutron::RouterInterface '%s' router:'%s', "
305                   "subnet:'%s'", name, router_name, subnet_name)
306         self.resources[name] = {
307             'type': 'OS::Neutron::RouterInterface',
308             'depends_on': [router_name, subnet_name],
309             'properties': {
310                 'router_id': {'get_resource': router_name},
311                 'subnet_id': {'get_resource': subnet_name}
312             }
313         }
314
315     def add_port(self, name, network_name, subnet_name, sec_group_id=None,
316                  provider=None):
317         """add to the template a named Neutron Port"""
318         log.debug("adding Neutron::Port '%s', network:'%s', subnet:'%s', "
319                   "secgroup:%s", name, network_name, subnet_name, sec_group_id)
320         self.resources[name] = {
321             'type': 'OS::Neutron::Port',
322             'depends_on': [subnet_name],
323             'properties': {
324                 'name': name,
325                 'fixed_ips': [{'subnet': {'get_resource': subnet_name}}],
326                 'network_id': {'get_resource': network_name},
327                 'replacement_policy': 'AUTO',
328             }
329         }
330
331         if provider == PROVIDER_SRIOV:
332             self.resources[name]['properties']['binding:vnic_type'] = \
333                 'direct'
334
335         if sec_group_id:
336             self.resources[name]['depends_on'].append(sec_group_id)
337             self.resources[name]['properties']['security_groups'] = \
338                 [sec_group_id]
339
340         self._template['outputs'][name] = {
341             'description': 'Address for interface %s' % name,
342             'value': {'get_attr': [name, 'fixed_ips', 0, 'ip_address']}
343         }
344         self._template['outputs'][name + "-subnet_id"] = {
345             'description': 'Address for interface %s' % name,
346             'value': {'get_attr': [name, 'fixed_ips', 0, 'subnet_id']}
347         }
348         self._template['outputs'][name + "-mac_address"] = {
349             'description': 'MAC Address for interface %s' % name,
350             'value': {'get_attr': [name, 'mac_address']}
351         }
352         self._template['outputs'][name + "-device_id"] = {
353             'description': 'Device ID for interface %s' % name,
354             'value': {'get_attr': [name, 'device_id']}
355         }
356         self._template['outputs'][name + "-network_id"] = {
357             'description': 'Network ID for interface %s' % name,
358             'value': {'get_attr': [name, 'network_id']}
359         }
360
361     def add_floating_ip(self, name, network_name, port_name, router_if_name,
362                         secgroup_name=None):
363         """add to the template a Nova FloatingIP resource
364         see: https://bugs.launchpad.net/heat/+bug/1299259
365         """
366         log.debug("adding Nova::FloatingIP '%s', network '%s', port '%s', "
367                   "rif '%s'", name, network_name, port_name, router_if_name)
368
369         self.resources[name] = {
370             'type': 'OS::Nova::FloatingIP',
371             'depends_on': [port_name, router_if_name],
372             'properties': {
373                 'pool': network_name
374             }
375         }
376
377         if secgroup_name:
378             self.resources[name]["depends_on"].append(secgroup_name)
379
380         self._template['outputs'][name] = {
381             'description': 'floating ip %s' % name,
382             'value': {'get_attr': [name, 'ip']}
383         }
384
385     def add_floating_ip_association(self, name, floating_ip_name, port_name):
386         """add to the template a Nova FloatingIP Association resource
387         """
388         log.debug("adding Nova::FloatingIPAssociation '%s', server '%s', "
389                   "floating_ip '%s'", name, port_name, floating_ip_name)
390
391         self.resources[name] = {
392             'type': 'OS::Neutron::FloatingIPAssociation',
393             'depends_on': [port_name],
394             'properties': {
395                 'floatingip_id': {'get_resource': floating_ip_name},
396                 'port_id': {'get_resource': port_name}
397             }
398         }
399
400     def add_keypair(self, name, key_uuid):
401         """add to the template a Nova KeyPair"""
402         log.debug("adding Nova::KeyPair '%s'", name)
403         self.resources[name] = {
404             'type': 'OS::Nova::KeyPair',
405             'properties': {
406                 'name': name,
407                 # resource_string returns bytes, so we must decode to unicode
408                 'public_key': encodeutils.safe_decode(
409                     pkg_resources.resource_string(
410                         'yardstick.resources',
411                         'files/yardstick_key-' +
412                         get_short_key_uuid(key_uuid) + '.pub'),
413                     'utf-8')
414             }
415         }
416
417     def add_servergroup(self, name, policy):
418         """add to the template a Nova ServerGroup"""
419         log.debug("adding Nova::ServerGroup '%s', policy '%s'", name, policy)
420         if policy not in ["anti-affinity", "affinity"]:
421             raise ValueError(policy)
422
423         self.resources[name] = {
424             'type': 'OS::Nova::ServerGroup',
425             'properties': {
426                 'name': name,
427                 'policies': [policy]
428             }
429         }
430
431         self._template['outputs'][name] = {
432             'description': 'ID Server Group %s' % name,
433             'value': {'get_resource': name}
434         }
435
436     def add_security_group(self, name):
437         """add to the template a Neutron SecurityGroup"""
438         log.debug("adding Neutron::SecurityGroup '%s'", name)
439         self.resources[name] = {
440             'type': 'OS::Neutron::SecurityGroup',
441             'properties': {
442                 'name': name,
443                 'description': "Group allowing icmp and upd/tcp on all ports",
444                 'rules': [
445                     {'remote_ip_prefix': '0.0.0.0/0',
446                      'protocol': 'tcp',
447                      'port_range_min': '1',
448                      'port_range_max': '65535'},
449                     {'remote_ip_prefix': '0.0.0.0/0',
450                      'protocol': 'udp',
451                      'port_range_min': '1',
452                      'port_range_max': '65535'},
453                     {'remote_ip_prefix': '0.0.0.0/0',
454                      'protocol': 'icmp'}
455                 ]
456             }
457         }
458
459         self._template['outputs'][name] = {
460             'description': 'ID of Security Group',
461             'value': {'get_resource': name}
462         }
463
464     def add_server(self, name, image, flavor, flavors, ports=None,
465                    networks=None, scheduler_hints=None, user=None,
466                    key_name=None, user_data=None, metadata=None,
467                    additional_properties=None):
468         """add to the template a Nova Server"""
469         log.debug("adding Nova::Server '%s', image '%s', flavor '%s', "
470                   "ports %s", name, image, flavor, ports)
471
472         self.resources[name] = {
473             'type': 'OS::Nova::Server',
474             'depends_on': []
475         }
476
477         server_properties = {
478             'name': name,
479             'image': image,
480             'flavor': {},
481             'networks': []  # list of dictionaries
482         }
483
484         if flavor in flavors:
485             self.resources[name]['depends_on'].append(flavor)
486             server_properties["flavor"] = {'get_resource': flavor}
487         else:
488             server_properties["flavor"] = flavor
489
490         if user:
491             server_properties['admin_user'] = user
492
493         if key_name:
494             self.resources[name]['depends_on'].append(key_name)
495             server_properties['key_name'] = {'get_resource': key_name}
496
497         if ports:
498             self.resources[name]['depends_on'].extend(ports)
499             for port in ports:
500                 server_properties['networks'].append(
501                     {'port': {'get_resource': port}}
502                 )
503
504         if networks:
505             for i, _ in enumerate(networks):
506                 server_properties['networks'].append({'network': networks[i]})
507
508         if scheduler_hints:
509             server_properties['scheduler_hints'] = scheduler_hints
510
511         if user_data:
512             server_properties['user_data'] = user_data
513
514         if metadata:
515             assert isinstance(metadata, collections.Mapping)
516             server_properties['metadata'] = metadata
517
518         if additional_properties:
519             assert isinstance(additional_properties, collections.Mapping)
520             for prop in additional_properties:
521                 server_properties[prop] = additional_properties[prop]
522
523         server_properties['config_drive'] = True
524
525         self.resources[name]['properties'] = server_properties
526
527         self._template['outputs'][name] = {
528             'description': 'VM UUID',
529             'value': {'get_resource': name}
530         }
531
532     HEAT_WAIT_LOOP_INTERVAL = 2
533
534     def create(self, block=True, timeout=3600):
535         """
536         creates a template in the target cloud using heat
537         returns a dict with the requested output values from the template
538
539         :param block: Wait for Heat create to finish
540         :type block: bool
541         :param: timeout: timeout in seconds for Heat create, default 3600s
542         :type timeout: int
543         """
544         log.info("Creating stack '%s'", self.name)
545
546         # create stack early to support cleanup, e.g. ctrl-c while waiting
547         stack = HeatStack(self.name)
548
549         heat_client = self.heat_client
550         start_time = time.time()
551         stack.uuid = self.uuid = heat_client.stacks.create(
552             stack_name=self.name, template=self._template,
553             parameters=self.heat_parameters)['stack']['id']
554
555         if not block:
556             self.outputs = stack.outputs = {}
557             return stack
558
559         time_limit = start_time + timeout
560         for status in iter(self.status, u'CREATE_COMPLETE'):
561             log.debug("stack state %s", status)
562             if status == u'CREATE_FAILED':
563                 raise RuntimeError(
564                     heat_client.stacks.get(self.uuid).stack_status_reason)
565             if time.time() > time_limit:
566                 raise RuntimeError("Heat stack create timeout")
567
568             time.sleep(self.HEAT_WAIT_LOOP_INTERVAL)
569
570         end_time = time.time()
571         outputs = heat_client.stacks.get(self.uuid).outputs
572         log.info("Created stack '%s' in %d secs",
573                  self.name, end_time - start_time)
574
575         # keep outputs as unicode
576         self.outputs = {output["output_key"]: output["output_value"] for output
577                         in outputs}
578
579         stack.outputs = self.outputs
580         return stack