Synchronise the openstack bugs
[parser.git] / tosca2heat / heat-translator / translator / hot / syntax / hot_resource.py
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 from collections import OrderedDict
14 import logging
15 import os
16 import six
17
18 from toscaparser.elements.interfaces import InterfacesDef
19 from toscaparser.functions import GetInput
20 from toscaparser.nodetemplate import NodeTemplate
21 from toscaparser.utils.gettextutils import _
22
23
24 SECTIONS = (TYPE, PROPERTIES, MEDADATA, DEPENDS_ON, UPDATE_POLICY,
25             DELETION_POLICY) = \
26            ('type', 'properties', 'metadata',
27             'depends_on', 'update_policy', 'deletion_policy')
28 log = logging.getLogger('heat-translator')
29
30
31 class HotResource(object):
32     '''Base class for TOSCA node type translation to Heat resource type.'''
33
34     def __init__(self, nodetemplate, name=None, type=None, properties=None,
35                  metadata=None, depends_on=None,
36                  update_policy=None, deletion_policy=None):
37         log.debug(_('Translating TOSCA node type to HOT resource type.'))
38         self.nodetemplate = nodetemplate
39         if name:
40             self.name = name
41         else:
42             self.name = nodetemplate.name
43         self.type = type
44         self.properties = properties or {}
45         # special case for HOT softwareconfig
46         if type == 'OS::Heat::SoftwareConfig':
47             config = self.properties.get('config')
48             if config:
49                 implementation_artifact = config.get('get_file')
50                 if implementation_artifact:
51                     filename, file_extension = os.path.splitext(
52                         implementation_artifact)
53                     file_extension = file_extension.lower()
54                     # artifact_types should be read to find the exact script
55                     # type, unfortunately artifact_types doesn't seem to be
56                     # supported by the parser
57                     if file_extension == '.ansible' \
58                             or file_extension == '.yaml' \
59                             or file_extension == '.yml':
60                         self.properties['group'] = 'ansible'
61                     if file_extension == '.pp':
62                         self.properties['group'] = 'puppet'
63
64             if self.properties.get('group') is None:
65                 self.properties['group'] = 'script'
66
67         self.metadata = metadata
68
69         # The difference between depends_on and depends_on_nodes is
70         # that depends_on defines dependency in the context of the
71         # HOT template and it is used during the template output.
72         # Depends_on_nodes defines the direct dependency between the
73         # tosca nodes and is not used during the output of the
74         # HOT template but for internal processing only. When a tosca
75         # node depends on another node it will be always added to
76         # depends_on_nodes but not always to depends_on. For example
77         # if the source of dependency is a server, the dependency will
78         # be added as properties.get_resource and not depends_on
79         if depends_on:
80             self.depends_on = depends_on
81             self.depends_on_nodes = depends_on
82         else:
83             self.depends_on = []
84             self.depends_on_nodes = []
85         self.update_policy = update_policy
86         self.deletion_policy = deletion_policy
87         self.group_dependencies = {}
88         # if hide_resource is set to true, then this resource will not be
89         # generated in the output yaml.
90         self.hide_resource = False
91
92     def handle_properties(self):
93         # the property can hold a value or the intrinsic function get_input
94         # for value, copy it
95         # for get_input, convert to get_param
96         for prop in self.nodetemplate.get_properties_objects():
97             pass
98
99     def handle_life_cycle(self):
100         hot_resources = []
101         deploy_lookup = {}
102         # TODO(anyone):  sequence for life cycle needs to cover different
103         # scenarios and cannot be fixed or hard coded here
104         operations_deploy_sequence = ['create', 'configure', 'start']
105
106         operations = HotResource.get_all_operations(self.nodetemplate)
107
108         # create HotResource for each operation used for deployment:
109         # create, start, configure
110         # ignore the other operations
111         # observe the order:  create, start, configure
112         # use the current HotResource for the first operation in this order
113
114         # hold the original name since it will be changed during
115         # the transformation
116         node_name = self.name
117         reserve_current = 'NONE'
118
119         for operation in operations_deploy_sequence:
120             if operation in operations.keys():
121                 reserve_current = operation
122                 break
123
124         # create the set of SoftwareDeployment and SoftwareConfig for
125         # the interface operations
126         hosting_server = None
127         if self.nodetemplate.requirements is not None:
128             hosting_server = self._get_hosting_server()
129         for operation in operations.values():
130             if operation.name in operations_deploy_sequence:
131                 config_name = node_name + '_' + operation.name + '_config'
132                 deploy_name = node_name + '_' + operation.name + '_deploy'
133                 hot_resources.append(
134                     HotResource(self.nodetemplate,
135                                 config_name,
136                                 'OS::Heat::SoftwareConfig',
137                                 {'config':
138                                     {'get_file': operation.implementation}}))
139
140                 # hosting_server is None if requirements is None
141                 hosting_on_server = (hosting_server.name if
142                                      hosting_server else None)
143                 base_type = HotResource.get_base_type(
144                     self.nodetemplate.type_definition).type
145                 # handle interfaces directly defined on a compute
146                 if hosting_on_server is None \
147                     and base_type == 'tosca.nodes.Compute':
148                     hosting_on_server = self.name
149
150                 if operation.name == reserve_current and \
151                     base_type != 'tosca.nodes.Compute':
152                     deploy_resource = self
153                     self.name = deploy_name
154                     self.type = 'OS::Heat::SoftwareDeployment'
155                     self.properties = {'config': {'get_resource': config_name},
156                                        'server': {'get_resource':
157                                                   hosting_on_server}}
158                     deploy_lookup[operation] = self
159                 else:
160                     sd_config = {'config': {'get_resource': config_name},
161                                  'server': {'get_resource':
162                                             hosting_on_server}}
163                     deploy_resource = \
164                         HotResource(self.nodetemplate,
165                                     deploy_name,
166                                     'OS::Heat::SoftwareDeployment',
167                                     sd_config)
168                     hot_resources.append(deploy_resource)
169                     deploy_lookup[operation] = deploy_resource
170                 lifecycle_inputs = self._get_lifecycle_inputs(operation)
171                 if lifecycle_inputs:
172                     deploy_resource.properties['input_values'] = \
173                         lifecycle_inputs
174
175         # Add dependencies for the set of HOT resources in the sequence defined
176         # in operations_deploy_sequence
177         # TODO(anyone): find some better way to encode this implicit sequence
178         group = {}
179         op_index_max = -1
180         for op, hot in deploy_lookup.items():
181             # position to determine potential preceding nodes
182             op_index = operations_deploy_sequence.index(op.name)
183             if op_index > op_index_max:
184                 op_index_max = op_index
185             for preceding_op_name in \
186                     reversed(operations_deploy_sequence[:op_index]):
187                 preceding_hot = deploy_lookup.get(
188                     operations.get(preceding_op_name))
189                 if preceding_hot:
190                     hot.depends_on.append(preceding_hot)
191                     hot.depends_on_nodes.append(preceding_hot)
192                     group[preceding_hot] = hot
193                     break
194
195         if op_index_max >= 0:
196             last_deploy = deploy_lookup.get(operations.get(
197                 operations_deploy_sequence[op_index_max]))
198         else:
199             last_deploy = None
200
201         # save this dependency chain in the set of HOT resources
202         self.group_dependencies.update(group)
203         for hot in hot_resources:
204             hot.group_dependencies.update(group)
205
206         return hot_resources, deploy_lookup, last_deploy
207
208     def handle_connectsto(self, tosca_source, tosca_target, hot_source,
209                           hot_target, config_location, operation):
210         # The ConnectsTo relationship causes a configuration operation in
211         # the target.
212         # This hot resource is the software config portion in the HOT template
213         # This method adds the matching software deployment with the proper
214         # target server and dependency
215         if config_location == 'target':
216             hosting_server = hot_target._get_hosting_server()
217             hot_depends = hot_target
218         elif config_location == 'source':
219             hosting_server = self._get_hosting_server()
220             hot_depends = hot_source
221         deploy_name = tosca_source.name + '_' + tosca_target.name + \
222             '_connect_deploy'
223         sd_config = {'config': {'get_resource': self.name},
224                      'server': {'get_resource': hosting_server.name}}
225         deploy_resource = \
226             HotResource(self.nodetemplate,
227                         deploy_name,
228                         'OS::Heat::SoftwareDeployment',
229                         sd_config,
230                         depends_on=[hot_depends])
231         connect_inputs = self._get_connect_inputs(config_location, operation)
232         if connect_inputs:
233             deploy_resource.properties['input_values'] = connect_inputs
234
235         return deploy_resource
236
237     def handle_expansion(self):
238         pass
239
240     def handle_hosting(self):
241         # handle hosting server for the OS:HEAT::SoftwareDeployment
242         # from the TOSCA nodetemplate, traverse the relationship chain
243         # down to the server
244         if self.type == 'OS::Heat::SoftwareDeployment':
245             # skip if already have hosting
246             # If type is NodeTemplate, look up corresponding HotResrouce
247             host_server = self.properties.get('server')
248             if host_server is None or not host_server['get_resource']:
249                 raise Exception(_("Internal Error: expecting host "
250                                   "in software deployment"))
251             elif isinstance(host_server['get_resource'], NodeTemplate):
252                 self.properties['server']['get_resource'] = \
253                     host_server['get_resource'].name
254
255     def top_of_chain(self):
256         dependent = self.group_dependencies.get(self)
257         if dependent is None:
258             return self
259         else:
260             return dependent.top_of_chain()
261
262     def get_dict_output(self):
263         resource_sections = OrderedDict()
264         resource_sections[TYPE] = self.type
265         if self.properties:
266             resource_sections[PROPERTIES] = self.properties
267         if self.metadata:
268             resource_sections[MEDADATA] = self.metadata
269         if self.depends_on:
270             resource_sections[DEPENDS_ON] = []
271             for depend in self.depends_on:
272                 resource_sections[DEPENDS_ON].append(depend.name)
273         if self.update_policy:
274             resource_sections[UPDATE_POLICY] = self.update_policy
275         if self.deletion_policy:
276             resource_sections[DELETION_POLICY] = self.deletion_policy
277
278         return {self.name: resource_sections}
279
280     def _get_lifecycle_inputs(self, operation):
281         # check if this lifecycle operation has input values specified
282         # extract and convert to HOT format
283         if isinstance(operation.value, six.string_types):
284             # the operation has a static string
285             return {}
286         else:
287             # the operation is a dict {'implemenation': xxx, 'input': yyy}
288             inputs = operation.value.get('inputs')
289             deploy_inputs = {}
290             if inputs:
291                 for name, value in six.iteritems(inputs):
292                     deploy_inputs[name] = value
293             return deploy_inputs
294
295     def _get_connect_inputs(self, config_location, operation):
296         if config_location == 'target':
297             inputs = operation.get('pre_configure_target').get('inputs')
298         elif config_location == 'source':
299             inputs = operation.get('pre_configure_source').get('inputs')
300         deploy_inputs = {}
301         if inputs:
302             for name, value in six.iteritems(inputs):
303                 deploy_inputs[name] = value
304         return deploy_inputs
305
306     def _get_hosting_server(self, node_template=None):
307         # find the server that hosts this software by checking the
308         # requirements and following the hosting chain
309         this_node_template = self.nodetemplate \
310             if node_template is None else node_template
311         for requirement in this_node_template.requirements:
312             for requirement_name, assignment in six.iteritems(requirement):
313                 for check_node in this_node_template.related_nodes:
314                     # check if the capability is Container
315                     if isinstance(assignment, dict):
316                         node_name = assignment.get('node')
317                     else:
318                         node_name = assignment
319                     if node_name and node_name == check_node.name:
320                         if self._is_container_type(requirement_name,
321                                                    check_node):
322                             return check_node
323                         elif check_node.related_nodes:
324                             return self._get_hosting_server(check_node)
325         return None
326
327     def _is_container_type(self, requirement_name, node):
328         # capability is a list of dict
329         # For now just check if it's type tosca.nodes.Compute
330         # TODO(anyone): match up requirement and capability
331         base_type = HotResource.get_base_type(node.type_definition)
332         if base_type.type == 'tosca.nodes.Compute':
333             return True
334         else:
335             return False
336
337     def get_hot_attribute(self, attribute, args):
338         # this is a place holder and should be implemented by the subclass
339         # if translation is needed for the particular attribute
340         raise Exception(_("No translation in TOSCA type {0} for attribute "
341                           "{1}").format(self.nodetemplate.type, attribute))
342
343     def get_tosca_props(self):
344         tosca_props = {}
345         for prop in self.nodetemplate.get_properties_objects():
346             if isinstance(prop.value, GetInput):
347                 tosca_props[prop.name] = {'get_param': prop.value.input_name}
348             else:
349                 tosca_props[prop.name] = prop.value
350         return tosca_props
351
352     @staticmethod
353     def get_all_operations(node):
354         operations = {}
355         for operation in node.interfaces:
356             operations[operation.name] = operation
357
358         node_type = node.type_definition
359         if isinstance(node_type, str) or \
360             node_type.type == "tosca.policies.Placement" or \
361             node_type.type == "tosca.policies.Colocate" or \
362             node_type.type == "tosca.policies.Antilocate":
363                 return operations
364
365         while True:
366             type_operations = HotResource._get_interface_operations_from_type(
367                 node_type, node, 'Standard')
368             type_operations.update(operations)
369             operations = type_operations
370
371             if node_type.parent_type is not None:
372                 node_type = node_type.parent_type
373             else:
374                 return operations
375
376     @staticmethod
377     def _get_interface_operations_from_type(node_type, node, lifecycle_name):
378         operations = {}
379         if isinstance(node_type, str) or \
380             node_type.type == "tosca.policies.Placement" or \
381             node_type.type == "tosca.policies.Colocate" or \
382             node_type.type == "tosca.policies.Antilocate":
383                 return operations
384         if node_type.interfaces and lifecycle_name in node_type.interfaces:
385             for name, elems in node_type.interfaces[lifecycle_name].items():
386                 # ignore empty operations (only type)
387                 # ignore global interface inputs,
388                 # concrete inputs are on the operations themselves
389                 if name != 'type' and name != 'inputs':
390                     operations[name] = InterfacesDef(node_type,
391                                                      lifecycle_name,
392                                                      node, name, elems)
393         return operations
394
395     @staticmethod
396     def get_base_type(node_type):
397         if node_type.parent_type is not None:
398             if node_type.parent_type.type.endswith('.Root') or \
399                node_type.type == "tosca.policies.Colocate" or \
400                node_type.type == "tosca.policies.Antilocate":
401                 return node_type
402             else:
403                 return HotResource.get_base_type(node_type.parent_type)
404         else:
405             return node_type