1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements. See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License. You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 from StringIO import StringIO # Note: cStringIO does not support Unicode
19 from aria.utils.collections import FrozenList
20 from aria.utils.formatting import (as_raw, safe_repr)
21 from aria.utils.type import full_type_name
22 from aria.parser import implements_specification
23 from aria.parser.exceptions import InvalidValueError
24 from aria.parser.validation import Issue
25 from aria.modeling.exceptions import CannotEvaluateFunctionException
26 from aria.modeling.models import (Node, NodeTemplate, Relationship, RelationshipTemplate)
27 from aria.modeling.functions import (Function, Evaluation)
34 @implements_specification('4.3.1', 'tosca-simple-1.0')
35 class Concat(Function):
37 The ``concat`` function is used to concatenate two or more string values within a TOSCA
41 def __init__(self, context, presentation, argument):
42 self.locator = presentation._locator
44 if not isinstance(argument, list):
45 raise InvalidValueError(
46 'function "concat" argument must be a list of string expressions: {0}'
47 .format(safe_repr(argument)),
50 string_expressions = []
51 for index, an_argument in enumerate(argument):
52 string_expressions.append(parse_string_expression(context, presentation, 'concat',
53 index, None, an_argument))
54 self.string_expressions = FrozenList(string_expressions)
58 string_expressions = []
59 for string_expression in self.string_expressions:
60 if hasattr(string_expression, 'as_raw'):
61 string_expression = as_raw(string_expression)
62 string_expressions.append(string_expression)
63 return {'concat': string_expressions}
65 def __evaluate__(self, container_holder):
68 for e in self.string_expressions:
69 e, final = evaluate(e, final, container_holder)
71 value.write(unicode(e))
72 value = value.getvalue() or u''
73 return Evaluation(value, final)
76 @implements_specification('4.3.2', 'tosca-simple-1.0')
77 class Token(Function):
79 The ``token`` function is used within a TOSCA service template on a string to parse out
80 (tokenize) substrings separated by one or more token characters within a larger string.
83 def __init__(self, context, presentation, argument):
84 self.locator = presentation._locator
86 if (not isinstance(argument, list)) or (len(argument) != 3):
87 raise InvalidValueError('function "token" argument must be a list of 3 parameters: {0}'
88 .format(safe_repr(argument)),
91 self.string_with_tokens = parse_string_expression(context, presentation, 'token', 0,
92 'the string to tokenize', argument[0])
93 self.string_of_token_chars = parse_string_expression(context, presentation, 'token', 1,
94 'the token separator characters',
96 self.substring_index = parse_int(context, presentation, 'token', 2,
97 'the 0-based index of the token to return', argument[2])
101 string_with_tokens = self.string_with_tokens
102 if hasattr(string_with_tokens, 'as_raw'):
103 string_with_tokens = as_raw(string_with_tokens)
104 string_of_token_chars = self.string_of_token_chars
105 if hasattr(string_of_token_chars, 'as_raw'):
106 string_of_token_chars = as_raw(string_of_token_chars)
107 return {'token': [string_with_tokens, string_of_token_chars, self.substring_index]}
109 def __evaluate__(self, container_holder):
111 string_with_tokens, final = evaluate(self.string_with_tokens, final, container_holder)
112 string_of_token_chars, final = evaluate(self.string_of_token_chars, final, container_holder)
114 if string_of_token_chars:
115 regex = '[' + ''.join(re.escape(c) for c in string_of_token_chars) + ']'
116 split = re.split(regex, string_with_tokens)
117 if self.substring_index < len(split):
118 return Evaluation(split[self.substring_index], final)
120 raise CannotEvaluateFunctionException()
127 @implements_specification('4.4.1', 'tosca-simple-1.0')
128 class GetInput(Function):
130 The ``get_input`` function is used to retrieve the values of properties declared within the
131 inputs section of a TOSCA Service Template.
134 def __init__(self, context, presentation, argument):
135 self.locator = presentation._locator
137 self.input_property_name = parse_string_expression(context, presentation, 'get_input',
138 None, 'the input property name',
141 if isinstance(self.input_property_name, basestring):
142 the_input = context.presentation.get_from_dict('service_template', 'topology_template',
143 'inputs', self.input_property_name)
144 if the_input is None:
145 raise InvalidValueError(
146 'function "get_input" argument is not a valid input name: {0}'
147 .format(safe_repr(argument)),
148 locator=self.locator)
152 return {'get_input': as_raw(self.input_property_name)}
154 def __evaluate__(self, container_holder):
155 service = container_holder.service
157 raise CannotEvaluateFunctionException()
159 value = service.inputs.get(self.input_property_name)
160 if value is not None:
162 return Evaluation(value, False) # We never return final evaluations!
164 raise InvalidValueError(
165 'function "get_input" argument is not a valid input name: {0}'
166 .format(safe_repr(self.input_property_name)),
167 locator=self.locator)
170 @implements_specification('4.4.2', 'tosca-simple-1.0')
171 class GetProperty(Function):
173 The ``get_property`` function is used to retrieve property values between modelable entities
174 defined in the same service template.
177 def __init__(self, context, presentation, argument):
178 self.locator = presentation._locator
180 if (not isinstance(argument, list)) or (len(argument) < 2):
181 raise InvalidValueError(
182 'function "get_property" argument must be a list of at least 2 string expressions: '
183 '{0}'.format(safe_repr(argument)),
184 locator=self.locator)
186 self.modelable_entity_name = parse_modelable_entity_name(context, presentation,
187 'get_property', 0, argument[0])
188 # The first of these will be tried as a req-or-cap name:
189 self.nested_property_name_or_index = argument[1:]
193 return {'get_property': [self.modelable_entity_name] + self.nested_property_name_or_index}
195 def __evaluate__(self, container_holder):
196 modelable_entities = get_modelable_entities(container_holder, 'get_property', self.locator,
197 self.modelable_entity_name)
198 req_or_cap_name = self.nested_property_name_or_index[0]
200 for modelable_entity in modelable_entities:
203 # First argument refers to a requirement template?
204 if hasattr(modelable_entity, 'requirement_templates') \
205 and modelable_entity.requirement_templates \
206 and (req_or_cap_name in [v.name for v in modelable_entity.requirement_templates]):
207 for requirement in modelable_entity.requirement_templates:
208 if requirement.name == req_or_cap_name:
210 raise CannotEvaluateFunctionException()
211 # First argument refers to a capability?
212 elif hasattr(modelable_entity, 'capabilities') \
213 and modelable_entity.capabilities \
214 and (req_or_cap_name in modelable_entity.capabilities):
215 properties = modelable_entity.capabilities[req_or_cap_name].properties
216 nested_property_name_or_index = self.nested_property_name_or_index[1:]
217 # First argument refers to a capability template?
218 elif hasattr(modelable_entity, 'capability_templates') \
219 and modelable_entity.capability_templates \
220 and (req_or_cap_name in modelable_entity.capability_templates):
221 properties = modelable_entity.capability_templates[req_or_cap_name].properties
222 nested_property_name_or_index = self.nested_property_name_or_index[1:]
224 properties = modelable_entity.properties
225 nested_property_name_or_index = self.nested_property_name_or_index
227 evaluation = get_modelable_entity_parameter(modelable_entity, properties,
228 nested_property_name_or_index)
229 if evaluation is not None:
232 raise InvalidValueError(
233 'function "get_property" could not find "{0}" in modelable entity "{1}"'
234 .format('.'.join(self.nested_property_name_or_index), self.modelable_entity_name),
235 locator=self.locator)
242 @implements_specification('4.5.1', 'tosca-simple-1.0')
243 class GetAttribute(Function):
245 The ``get_attribute`` function is used to retrieve the values of named attributes declared
246 by the referenced node or relationship template name.
249 def __init__(self, context, presentation, argument):
250 self.locator = presentation._locator
252 if (not isinstance(argument, list)) or (len(argument) < 2):
253 raise InvalidValueError(
254 'function "get_attribute" argument must be a list of at least 2 string expressions:'
255 ' {0}'.format(safe_repr(argument)),
256 locator=self.locator)
258 self.modelable_entity_name = parse_modelable_entity_name(context, presentation,
259 'get_attribute', 0, argument[0])
260 # The first of these will be tried as a req-or-cap name:
261 self.nested_attribute_name_or_index = argument[1:]
265 return {'get_attribute': [self.modelable_entity_name] + self.nested_attribute_name_or_index}
267 def __evaluate__(self, container_holder):
268 modelable_entities = get_modelable_entities(container_holder, 'get_attribute', self.locator,
269 self.modelable_entity_name)
270 for modelable_entity in modelable_entities:
271 attributes = modelable_entity.attributes
272 nested_attribute_name_or_index = self.nested_attribute_name_or_index
273 evaluation = get_modelable_entity_parameter(modelable_entity, attributes,
274 nested_attribute_name_or_index)
275 if evaluation is not None:
276 evaluation.final = False # We never return final evaluations!
279 raise InvalidValueError(
280 'function "get_attribute" could not find "{0}" in modelable entity "{1}"'
281 .format('.'.join(self.nested_attribute_name_or_index), self.modelable_entity_name),
282 locator=self.locator)
289 @implements_specification('4.6.1', 'tosca-simple-1.0') # pylint: disable=abstract-method
290 class GetOperationOutput(Function):
292 The ``get_operation_output`` function is used to retrieve the values of variables exposed /
293 exported from an interface operation.
296 def __init__(self, context, presentation, argument):
297 self.locator = presentation._locator
299 if (not isinstance(argument, list)) or (len(argument) != 4):
300 raise InvalidValueError(
301 'function "get_operation_output" argument must be a list of 4 parameters: {0}'
302 .format(safe_repr(argument)),
303 locator=self.locator)
305 self.modelable_entity_name = parse_string_expression(context, presentation,
306 'get_operation_output', 0,
307 'modelable entity name', argument[0])
308 self.interface_name = parse_string_expression(context, presentation, 'get_operation_output',
309 1, 'the interface name', argument[1])
310 self.operation_name = parse_string_expression(context, presentation, 'get_operation_output',
311 2, 'the operation name', argument[2])
312 self.output_variable_name = parse_string_expression(context, presentation,
313 'get_operation_output', 3,
314 'the output name', argument[3])
318 interface_name = self.interface_name
319 if hasattr(interface_name, 'as_raw'):
320 interface_name = as_raw(interface_name)
321 operation_name = self.operation_name
322 if hasattr(operation_name, 'as_raw'):
323 operation_name = as_raw(operation_name)
324 output_variable_name = self.output_variable_name
325 if hasattr(output_variable_name, 'as_raw'):
326 output_variable_name = as_raw(output_variable_name)
327 return {'get_operation_output': [self.modelable_entity_name, interface_name, operation_name,
328 output_variable_name]}
335 @implements_specification('4.7.1', 'tosca-simple-1.0')
336 class GetNodesOfType(Function):
338 The ``get_nodes_of_type`` function can be used to retrieve a list of all known instances of
339 nodes of the declared Node Type.
342 def __init__(self, context, presentation, argument):
343 self.locator = presentation._locator
345 self.node_type_name = parse_string_expression(context, presentation, 'get_nodes_of_type',
346 None, 'the node type name', argument)
348 if isinstance(self.node_type_name, basestring):
349 node_types = context.presentation.get('service_template', 'node_types')
350 if (node_types is None) or (self.node_type_name not in node_types):
351 raise InvalidValueError(
352 'function "get_nodes_of_type" argument is not a valid node type name: {0}'
353 .format(safe_repr(argument)),
354 locator=self.locator)
358 node_type_name = self.node_type_name
359 if hasattr(node_type_name, 'as_raw'):
360 node_type_name = as_raw(node_type_name)
361 return {'get_nodes_of_type': node_type_name}
363 def __evaluate__(self, container):
371 @implements_specification('4.8.1', 'tosca-simple-1.0') # pylint: disable=abstract-method
372 class GetArtifact(Function):
374 The ``get_artifact`` function is used to retrieve artifact location between modelable
375 entities defined in the same service template.
378 def __init__(self, context, presentation, argument):
379 self.locator = presentation._locator
381 if (not isinstance(argument, list)) or (len(argument) < 2) or (len(argument) > 4):
382 raise InvalidValueError(
383 'function "get_artifact" argument must be a list of 2 to 4 parameters: {0}'
384 .format(safe_repr(argument)),
385 locator=self.locator)
387 self.modelable_entity_name = parse_string_expression(context, presentation, 'get_artifact',
388 0, 'modelable entity name',
390 self.artifact_name = parse_string_expression(context, presentation, 'get_artifact', 1,
391 'the artifact name', argument[1])
392 self.location = parse_string_expression(context, presentation, 'get_artifact', 2,
393 'the location or "LOCAL_FILE"', argument[2])
394 self.remove = parse_bool(context, presentation, 'get_artifact', 3, 'the removal flag',
399 artifact_name = self.artifact_name
400 if hasattr(artifact_name, 'as_raw'):
401 artifact_name = as_raw(artifact_name)
402 location = self.location
403 if hasattr(location, 'as_raw'):
404 location = as_raw(location)
405 return {'get_artifacts': [self.modelable_entity_name, artifact_name, location, self.remove]}
412 def get_function(context, presentation, value):
413 functions = context.presentation.presenter.functions
414 if isinstance(value, dict) and (len(value) == 1):
415 key = value.keys()[0]
418 return True, functions[key](context, presentation, value[key])
419 except InvalidValueError as e:
420 context.validation.report(issue=e.issue)
425 def parse_string_expression(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
426 is_function, func = get_function(context, presentation, value)
434 def parse_int(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
435 if not isinstance(value, int):
439 raise invalid_value(name, index, 'an integer', explanation, value,
440 presentation._locator)
444 def parse_bool(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument
445 if not isinstance(value, bool):
446 raise invalid_value(name, index, 'a boolean', explanation, value, presentation._locator)
450 def parse_modelable_entity_name(context, presentation, name, index, value):
451 value = parse_string_expression(context, presentation, name, index, 'the modelable entity name',
454 the_self, _ = parse_self(presentation)
456 raise invalid_modelable_entity_name(name, index, value, presentation._locator,
457 'a node template or a relationship template')
458 elif value == 'HOST':
459 _, self_variant = parse_self(presentation)
460 if self_variant != 'node_template':
461 raise invalid_modelable_entity_name(name, index, value, presentation._locator,
463 elif (value == 'SOURCE') or (value == 'TARGET'):
464 _, self_variant = parse_self(presentation)
465 if self_variant != 'relationship_template':
466 raise invalid_modelable_entity_name(name, index, value, presentation._locator,
467 'a relationship template')
468 elif isinstance(value, basestring):
470 context.presentation.get('service_template', 'topology_template', 'node_templates') \
472 relationship_templates = \
473 context.presentation.get('service_template', 'topology_template',
474 'relationship_templates') \
476 if (value not in node_templates) and (value not in relationship_templates):
477 raise InvalidValueError(
478 'function "{0}" parameter {1:d} is not a valid modelable entity name: {2}'
479 .format(name, index + 1, safe_repr(value)),
480 locator=presentation._locator, level=Issue.BETWEEN_TYPES)
484 def parse_self(presentation):
485 from ..types import (NodeType, RelationshipType)
486 from ..templates import (
487 NodeTemplate as NodeTemplatePresentation,
488 RelationshipTemplate as RelationshipTemplatePresentation
491 if presentation is None:
493 elif isinstance(presentation, NodeTemplatePresentation) or isinstance(presentation, NodeType):
494 return presentation, 'node_template'
495 elif isinstance(presentation, RelationshipTemplatePresentation) \
496 or isinstance(presentation, RelationshipType):
497 return presentation, 'relationship_template'
499 return parse_self(presentation._container)
502 def evaluate(value, final, container_holder):
504 Calls ``__evaluate__`` and passes on ``final`` state.
507 if hasattr(value, '__evaluate__'):
508 value = value.__evaluate__(container_holder)
511 return value.value, final
516 @implements_specification('4.1', 'tosca-simple-1.0')
517 def get_modelable_entities(container_holder, name, locator, modelable_entity_name):
519 The following keywords MAY be used in some TOSCA function in place of a TOSCA Node or
520 Relationship Template name.
523 if modelable_entity_name == 'SELF':
524 return get_self(container_holder, name, locator)
525 elif modelable_entity_name == 'HOST':
526 return get_hosts(container_holder, name, locator)
527 elif modelable_entity_name == 'SOURCE':
528 return get_source(container_holder, name, locator)
529 elif modelable_entity_name == 'TARGET':
530 return get_target(container_holder, name, locator)
531 elif isinstance(modelable_entity_name, basestring):
532 modelable_entities = []
534 service = container_holder.service
535 if service is not None:
536 for node in service.nodes.itervalues():
537 if node.node_template.name == modelable_entity_name:
538 modelable_entities.append(node)
540 service_template = container_holder.service_template
541 if service_template is not None:
542 for node_template in service_template.node_templates.itervalues():
543 if node_template.name == modelable_entity_name:
544 modelable_entities.append(node_template)
546 if not modelable_entities:
547 raise CannotEvaluateFunctionException()
549 return modelable_entities
551 raise InvalidValueError('function "{0}" could not find modelable entity "{1}"'
552 .format(name, modelable_entity_name),
556 def get_self(container_holder, name, locator):
558 A TOSCA orchestrator will interpret this keyword as the Node or Relationship Template instance
559 that contains the function at the time the function is evaluated.
562 container = container_holder.container
563 if (not isinstance(container, Node)) and \
564 (not isinstance(container, NodeTemplate)) and \
565 (not isinstance(container, Relationship)) and \
566 (not isinstance(container, RelationshipTemplate)):
567 raise InvalidValueError('function "{0}" refers to "SELF" but it is not contained in '
568 'a node or a relationship: {1}'.format(name,
569 full_type_name(container)),
575 def get_hosts(container_holder, name, locator):
577 A TOSCA orchestrator will interpret this keyword to refer to the all nodes that "host" the node
578 using this reference (i.e., as identified by its HostedOn relationship).
580 Specifically, TOSCA orchestrators that encounter this keyword when evaluating the get_attribute
581 or ``get_property`` functions SHALL search each node along the "HostedOn" relationship chain
582 starting at the immediate node that hosts the node where the function was evaluated (and then
583 that node's host node, and so forth) until a match is found or the "HostedOn" relationship chain
587 container = container_holder.container
588 if (not isinstance(container, Node)) and (not isinstance(container, NodeTemplate)):
589 raise InvalidValueError('function "{0}" refers to "HOST" but it is not contained in '
590 'a node: {1}'.format(name, full_type_name(container)),
593 if not isinstance(container, Node):
594 # NodeTemplate does not have "host"; we'll wait until instantiation
595 raise CannotEvaluateFunctionException()
597 host = container.host
599 # We might have a host later
600 raise CannotEvaluateFunctionException()
605 def get_source(container_holder, name, locator):
607 A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the
608 source end of the relationship that contains the referencing function.
611 container = container_holder.container
612 if (not isinstance(container, Relationship)) and \
613 (not isinstance(container, RelationshipTemplate)):
614 raise InvalidValueError('function "{0}" refers to "SOURCE" but it is not contained in '
615 'a relationship: {1}'.format(name, full_type_name(container)),
618 if not isinstance(container, RelationshipTemplate):
619 # RelationshipTemplate does not have "source_node"; we'll wait until instantiation
620 raise CannotEvaluateFunctionException()
622 return [container.source_node]
625 def get_target(container_holder, name, locator):
627 A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the
628 target end of the relationship that contains the referencing function.
631 container = container_holder.container
632 if (not isinstance(container, Relationship)) and \
633 (not isinstance(container, RelationshipTemplate)):
634 raise InvalidValueError('function "{0}" refers to "TARGET" but it is not contained in '
635 'a relationship: {1}'.format(name, full_type_name(container)),
638 if not isinstance(container, RelationshipTemplate):
639 # RelationshipTemplate does not have "target_node"; we'll wait until instantiation
640 raise CannotEvaluateFunctionException()
642 return [container.target_node]
645 def get_modelable_entity_parameter(modelable_entity, parameters, nested_parameter_name_or_index):
647 return Evaluation(None, True)
653 for name_or_index in nested_parameter_name_or_index:
654 if (isinstance(value, dict) and (name_or_index in value)) \
655 or ((isinstance(value, list) and (name_or_index < len(value)))):
656 value = value[name_or_index] # Parameter
657 # We are not using Parameter.value, but rather Parameter._value, because we want to make
658 # sure to get "final" (it is swallowed by Parameter.value)
659 value, final = evaluate(value._value, final, value)
664 return Evaluation(value, final) if found else None
667 def invalid_modelable_entity_name(name, index, value, locator, contexts):
668 return InvalidValueError('function "{0}" parameter {1:d} can be "{2}" only in {3}'
669 .format(name, index + 1, value, contexts),
670 locator=locator, level=Issue.FIELD)
673 def invalid_value(name, index, the_type, explanation, value, locator):
674 return InvalidValueError(
675 'function "{0}" {1} is not {2}{3}: {4}'
677 'parameter {0:d}'.format(index + 1) if index is not None else 'argument',
679 ', {0}'.format(explanation) if explanation is not None else '',
681 locator=locator, level=Issue.FIELD)