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