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
5 # http://www.apache.org/licenses/LICENSE-2.0
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
13 from collections import OrderedDict
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 _
24 SECTIONS = (TYPE, PROPERTIES, MEDADATA, DEPENDS_ON, UPDATE_POLICY,
26 ('type', 'properties', 'metadata',
27 'depends_on', 'update_policy', 'deletion_policy')
28 log = logging.getLogger('heat-translator')
31 class HotResource(object):
32 '''Base class for TOSCA node type translation to Heat resource type.'''
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
42 self.name = nodetemplate.name
44 self.properties = properties or {}
45 # special case for HOT softwareconfig
46 if type == 'OS::Heat::SoftwareConfig':
47 config = self.properties.get('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'
64 if self.properties.get('group') is None:
65 self.properties['group'] = 'script'
67 self.metadata = metadata
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
80 self.depends_on = depends_on
81 self.depends_on_nodes = 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
92 def handle_properties(self):
93 # the property can hold a value or the intrinsic function get_input
95 # for get_input, convert to get_param
96 for prop in self.nodetemplate.get_properties_objects():
99 def handle_life_cycle(self):
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']
106 operations = HotResource.get_all_operations(self.nodetemplate)
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
114 # hold the original name since it will be changed during
116 node_name = self.name
117 reserve_current = 'NONE'
119 for operation in operations_deploy_sequence:
120 if operation in operations.keys():
121 reserve_current = operation
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,
136 'OS::Heat::SoftwareConfig',
138 {'get_file': operation.implementation}}))
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
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':
158 deploy_lookup[operation] = self
160 sd_config = {'config': {'get_resource': config_name},
161 'server': {'get_resource':
164 HotResource(self.nodetemplate,
166 'OS::Heat::SoftwareDeployment',
168 hot_resources.append(deploy_resource)
169 deploy_lookup[operation] = deploy_resource
170 lifecycle_inputs = self._get_lifecycle_inputs(operation)
172 deploy_resource.properties['input_values'] = \
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
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))
190 hot.depends_on.append(preceding_hot)
191 hot.depends_on_nodes.append(preceding_hot)
192 group[preceding_hot] = hot
195 if op_index_max >= 0:
196 last_deploy = deploy_lookup.get(operations.get(
197 operations_deploy_sequence[op_index_max]))
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)
206 return hot_resources, deploy_lookup, last_deploy
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
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 + \
223 sd_config = {'config': {'get_resource': self.name},
224 'server': {'get_resource': hosting_server.name}}
226 HotResource(self.nodetemplate,
228 'OS::Heat::SoftwareDeployment',
230 depends_on=[hot_depends])
231 connect_inputs = self._get_connect_inputs(config_location, operation)
233 deploy_resource.properties['input_values'] = connect_inputs
235 return deploy_resource
237 def handle_expansion(self):
240 def handle_hosting(self):
241 # handle hosting server for the OS:HEAT::SoftwareDeployment
242 # from the TOSCA nodetemplate, traverse the relationship chain
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
255 def top_of_chain(self):
256 dependent = self.group_dependencies.get(self)
257 if dependent is None:
260 return dependent.top_of_chain()
262 def get_dict_output(self):
263 resource_sections = OrderedDict()
264 resource_sections[TYPE] = self.type
266 resource_sections[PROPERTIES] = self.properties
268 resource_sections[MEDADATA] = self.metadata
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
278 return {self.name: resource_sections}
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
287 # the operation is a dict {'implemenation': xxx, 'input': yyy}
288 inputs = operation.value.get('inputs')
291 for name, value in six.iteritems(inputs):
292 deploy_inputs[name] = value
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')
302 for name, value in six.iteritems(inputs):
303 deploy_inputs[name] = value
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')
318 node_name = assignment
319 if node_name and node_name == check_node.name:
320 if self._is_container_type(requirement_name,
323 elif check_node.related_nodes:
324 return self._get_hosting_server(check_node)
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':
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))
343 def get_tosca_props(self):
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}
349 tosca_props[prop.name] = prop.value
353 def get_all_operations(node):
355 for operation in node.interfaces:
356 operations[operation.name] = operation
358 node_type = node.type_definition
359 if isinstance(node_type, str) or \
360 node_type.is_derived_from("tosca.policies.Root"):
361 # node_type.type == "tosca.policies.Placement" or \
362 # node_type.type == "tosca.policies.Placement.Colocate" or \
363 # node_type.type == "tosca.policies.Placement.Antilocate":
367 type_operations = HotResource._get_interface_operations_from_type(
368 node_type, node, 'Standard')
369 type_operations.update(operations)
370 operations = type_operations
372 if node_type.parent_type is not None:
373 node_type = node_type.parent_type
378 def _get_interface_operations_from_type(node_type, node, lifecycle_name):
380 if isinstance(node_type, str) or \
381 node_type.is_derived_from("tosca.policies.Root"):
382 # node_type.type == "tosca.policies.Placement" or \
383 # node_type.type == "tosca.policies.Placement.Colocate" or \
384 # node_type.type == "tosca.policies.Placement.Antilocate":
386 if node_type.interfaces and lifecycle_name in node_type.interfaces:
387 for name, elems in node_type.interfaces[lifecycle_name].items():
388 # ignore empty operations (only type)
389 # ignore global interface inputs,
390 # concrete inputs are on the operations themselves
391 if name != 'type' and name != 'inputs':
392 operations[name] = InterfacesDef(node_type,
398 def get_base_type(node_type):
399 if node_type.parent_type is not None:
400 if node_type.parent_type.type.endswith('.Root') or \
401 node_type.type == "tosca.policies.Placement.Colocate" or \
402 node_type.type == "tosca.policies.Placement.Antilocate":
405 return HotResource.get_base_type(node_type.parent_type)