Repository: incubator-ariatosca Updated Branches: refs/heads/ARIA-139-attributes 6f349dd72 -> c42bb4032
Re-enable node_filter and fix it Project: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/commit/c42bb403 Tree: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/tree/c42bb403 Diff: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/diff/c42bb403 Branch: refs/heads/ARIA-139-attributes Commit: c42bb40328f03b4cc682a4cf3367c0b6d6696586 Parents: 6f349dd Author: Tal Liron <[email protected]> Authored: Fri Apr 28 17:10:59 2017 -0500 Committer: Tal Liron <[email protected]> Committed: Fri Apr 28 17:10:59 2017 -0500 ---------------------------------------------------------------------- aria/modeling/functions.py | 7 +- aria/modeling/service_common.py | 18 +- aria/modeling/service_template.py | 18 +- aria/parser/consumption/__init__.py | 2 +- .../simple_v1_0/__init__.py | 12 +- .../simple_v1_0/functions.py | 597 ---------------- .../simple_v1_0/modeling/__init__.py | 157 ++--- .../simple_v1_0/modeling/data_types.py | 2 +- .../simple_v1_0/modeling/functions.py | 687 +++++++++++++++++++ .../simple_v1_0/presenter.py | 4 +- .../node-cellar/node-cellar.yaml | 2 + 11 files changed, 768 insertions(+), 738 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/aria/modeling/functions.py ---------------------------------------------------------------------- diff --git a/aria/modeling/functions.py b/aria/modeling/functions.py index f0d6c81..e736144 100644 --- a/aria/modeling/functions.py +++ b/aria/modeling/functions.py @@ -57,7 +57,12 @@ class Evaluation(object): self.final = final -def evaluate(value, container_holder, report_issues=False): +class NodeTemplateConstraint(object): + def apply(self, target_node_template, source_node_template): + raise NotImplementedError + + +def evaluate(value, container_holder, report_issues=False): # pylint: disable=too-many-branches """ Recursively attempts to call ``__evaluate__``. If an evaluation occurred will return an :class:`Evaluation`, otherwise it will be None. If any evaluation is non-final, then the entire http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/aria/modeling/service_common.py ---------------------------------------------------------------------- diff --git a/aria/modeling/service_common.py b/aria/modeling/service_common.py index 9539979..25ea905 100644 --- a/aria/modeling/service_common.py +++ b/aria/modeling/service_common.py @@ -53,8 +53,8 @@ class ParameterBase(TemplateModelMixin): name = Column(Text) type_name = Column(Text) - _value = Column(PickleType) description = Column(Text) + _value = Column(PickleType) @property def value(self): @@ -62,7 +62,6 @@ class ParameterBase(TemplateModelMixin): if value is not None: evaluation = functions.evaluate(value, self) if evaluation is not None: - print '>>> EVALUATED' value = evaluation.value return value @@ -71,12 +70,12 @@ class ParameterBase(TemplateModelMixin): self._value = value @property - def container(self): + def container(self): # pylint: disable=too-many-return-statements,too-many-branches """ The container for this parameter, which would be another model. *All* parameters should have a container model. In case this property method fails to find - it, it will raise a ValueError, which should signify an orphaned parameter. + it, it will raise a ValueError, which should signify an abnormal, orphaned parameter. """ def get_interface_container(interface): @@ -117,7 +116,7 @@ class ParameterBase(TemplateModelMixin): artifact = self.properties_artifacts[0] return artifact.node elif self.properties_relationships: - relationship = self.properties_relationships[0] + relationship = self.properties_relationships[0] # pylint: disable=redefined-outer-name return relationship.source_node # Group elif self.properties_groups: @@ -193,6 +192,10 @@ class ParameterBase(TemplateModelMixin): @property def service(self): + """ + The :class:`Service` containing this parameter, or None if not contained in a service. + """ + from . import models container = self.container if isinstance(container, models.Service): @@ -203,6 +206,11 @@ class ParameterBase(TemplateModelMixin): @property def service_template(self): + """ + The :class:`ServiceTemplate` containing this parameter, or None if not contained in a + service template. + """ + from . import models container = self.container if isinstance(container, models.ServiceTemplate): http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/aria/modeling/service_template.py ---------------------------------------------------------------------- diff --git a/aria/modeling/service_template.py b/aria/modeling/service_template.py index ec9bed1..5e1c7a5 100644 --- a/aria/modeling/service_template.py +++ b/aria/modeling/service_template.py @@ -17,7 +17,6 @@ from __future__ import absolute_import # so we can import standard 'types' -from types import FunctionType from datetime import datetime from sqlalchemy import ( @@ -25,7 +24,8 @@ from sqlalchemy import ( Text, Integer, Boolean, - DateTime + DateTime, + PickleType ) from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.associationproxy import association_proxy @@ -426,7 +426,7 @@ class NodeTemplateBase(TemplateModelMixin): :ivar requirement_templates: Potential relationships with other nodes :vartype requirement_templates: [:class:`RequirementTemplate`] :ivar target_node_template_constraints: Constraints for filtering relationship targets - :vartype target_node_template_constraints: [:class:`FunctionType`] + :vartype target_node_template_constraints: [:class:`NodeTemplateConstraint`] :ivar service_template: Containing service template :vartype service_template: :class:`ServiceTemplate` :ivar group_templates: We are a member of these groups @@ -528,12 +528,12 @@ class NodeTemplateBase(TemplateModelMixin): default_instances = Column(Integer, default=1) min_instances = Column(Integer, default=0) max_instances = Column(Integer, default=None) - target_node_template_constraints = Column(modeling_types.StrictList(FunctionType)) + target_node_template_constraints = Column(PickleType) def is_target_node_valid(self, target_node_template): if self.target_node_template_constraints: for node_type_constraint in self.target_node_template_constraints: - if not node_type_constraint(target_node_template, self): + if not node_type_constraint.apply(target_node_template, self): return False return True @@ -1124,7 +1124,7 @@ class RequirementTemplateBase(TemplateModelMixin): :ivar target_capability_name: Name of capability in target node (optional) :vartype target_capability_name: basestring :ivar target_node_template_constraints: Constraints for filtering relationship targets - :vartype target_node_template_constraints: [:class:`FunctionType`] + :vartype target_node_template_constraints: [:class:`NodeTemplateConstraint`] :ivar relationship_template: Template for relationships (optional) :vartype relationship_template: :class:`RelationshipTemplate` :ivar node_template: Containing node template @@ -1226,7 +1226,7 @@ class RequirementTemplateBase(TemplateModelMixin): # endregion target_capability_name = Column(Text) - target_node_template_constraints = Column(modeling_types.StrictList(FunctionType)) + target_node_template_constraints = Column(PickleType) def find_target(self, source_node_template): context = ConsumptionContext.get_thread_local() @@ -1237,7 +1237,7 @@ class RequirementTemplateBase(TemplateModelMixin): context.validation.report('requirement "{0}" of node template "{1}" is for node ' 'template "{2}" but it does not match constraints'.format( self.name, - self.target_node_template_name, + self.target_node_template.name, source_node_template.name), level=validation.Issue.BETWEEN_TYPES) if (self.target_capability_type is not None) \ @@ -1555,7 +1555,7 @@ class CapabilityTemplateBase(TemplateModelMixin): # Apply requirement constraints if requirement.target_node_template_constraints: for node_type_constraint in requirement.target_node_template_constraints: - if not node_type_constraint(target_node_template, source_node_template): + if not node_type_constraint.apply(target_node_template, source_node_template): return False return True http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/aria/parser/consumption/__init__.py ---------------------------------------------------------------------- diff --git a/aria/parser/consumption/__init__.py b/aria/parser/consumption/__init__.py index 97b3db4..76e73be 100644 --- a/aria/parser/consumption/__init__.py +++ b/aria/parser/consumption/__init__.py @@ -51,6 +51,6 @@ __all__ = ( 'ValidateServiceInstance', 'ConfigureOperations', 'SatisfyRequirements', - 'ValidateCapabilities' + 'ValidateCapabilities', 'CoerceServiceInstanceValues' ) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/__init__.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/__init__.py b/extensions/aria_extension_tosca/simple_v1_0/__init__.py index 29df362..d701a1d 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/__init__.py +++ b/extensions/aria_extension_tosca/simple_v1_0/__init__.py @@ -30,8 +30,6 @@ from .types import (ArtifactType, DataType, CapabilityType, InterfaceType, Relat NodeType, GroupType, PolicyType) from .data_types import (Timestamp, Version, Range, List, Map, ScalarSize, ScalarTime, ScalarFrequency) -from .functions import (Concat, Token, GetInput, GetProperty, GetAttribute, GetOperationOutput, - GetNodesOfType, GetArtifact) MODULES = ( 'modeling', @@ -89,12 +87,4 @@ __all__ = ( 'Map', 'ScalarSize', 'ScalarTime', - 'ScalarFrequency', - 'Concat', - 'Token', - 'GetInput', - 'GetProperty', - 'GetAttribute', - 'GetOperationOutput', - 'GetNodesOfType', - 'GetArtifact') + 'ScalarFrequency') \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/functions.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/functions.py b/extensions/aria_extension_tosca/simple_v1_0/functions.py deleted file mode 100644 index c698953..0000000 --- a/extensions/aria_extension_tosca/simple_v1_0/functions.py +++ /dev/null @@ -1,597 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from cStringIO import StringIO - -from aria.utils.collections import FrozenList -from aria.utils.formatting import as_raw, safe_repr -from aria.parser import dsl_specification -from aria.parser.consumption import ConsumptionContext -from aria.parser.exceptions import InvalidValueError -from aria.parser.validation import Issue -from aria.modeling.exceptions import CannotEvaluateFunctionException -from aria.modeling.models import Parameter -from aria.modeling.functions import (Function, Evaluation) - - -# -# Intrinsic -# - -@dsl_specification('4.3.1', 'tosca-simple-1.0') -class Concat(Function): - """ - The :code:`concat` function is used to concatenate two or more string values within a TOSCA - service template. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if not isinstance(argument, list): - raise InvalidValueError( - 'function "concat" argument must be a list of string expressions: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - string_expressions = [] - for index, an_argument in enumerate(argument): - string_expressions.append(parse_string_expression(context, presentation, 'concat', - index, None, an_argument)) - self.string_expressions = FrozenList(string_expressions) - - @property - def as_raw(self): - string_expressions = [] - for string_expression in self.string_expressions: - if hasattr(string_expression, 'as_raw'): - string_expression = as_raw(string_expression) - string_expressions.append(string_expression) - return {'concat': string_expressions} - - def __evaluate__(self, container_holder): - final = True - value = StringIO() - for e in self.string_expressions: - if hasattr(e, '__evaluate__'): - e = e.__evaluate__(container_holder) - if not e.final: - final = False - value.write(str(e)) - return Evaluation(value.getvalue(), final) - - -@dsl_specification('4.3.2', 'tosca-simple-1.0') -class Token(Function): - """ - The :code:`token` function is used within a TOSCA service template on a string to parse out - (tokenize) substrings separated by one or more token characters within a larger string. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if (not isinstance(argument, list)) or (len(argument) != 3): - raise InvalidValueError('function "token" argument must be a list of 3 parameters: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - self.string_with_tokens = parse_string_expression(context, presentation, 'token', 0, - 'the string to tokenize', argument[0]) - self.string_of_token_chars = parse_string_expression(context, presentation, 'token', 1, - 'the token separator characters', - argument[1]) - self.substring_index = parse_int(context, presentation, 'token', 2, - 'the 0-based index of the token to return', argument[2]) - - @property - def as_raw(self): - string_with_tokens = self.string_with_tokens - if hasattr(string_with_tokens, 'as_raw'): - string_with_tokens = as_raw(string_with_tokens) - string_of_token_chars = self.string_with_tokens - if hasattr(string_of_token_chars, 'as_raw'): - string_of_token_chars = as_raw(string_of_token_chars) - return {'token': [string_with_tokens, string_of_token_chars, self.substring_index]} - - def __evaluate__(self, container_holder): - string_with_tokens = self.string_with_tokens - if hasattr(string_with_tokens, '__evaluate__'): - string_with_tokens = string_with_tokens.__evaluate__(container_holder) # pylint: disable=no-member - # TODO - -# -# Property -# - -@dsl_specification('4.4.1', 'tosca-simple-1.0') -class GetInput(Function): - """ - The :code:`get_input` function is used to retrieve the values of properties declared within the - inputs section of a TOSCA Service Template. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - self.input_property_name = parse_string_expression(context, presentation, 'get_input', - None, 'the input property name', - argument) - - if isinstance(self.input_property_name, basestring): - the_input = context.presentation.get_from_dict('service_template', 'topology_template', - 'inputs', self.input_property_name) - if the_input is None: - raise InvalidValueError( - 'function "get_input" argument is not a valid input name: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - @property - def as_raw(self): - return {'get_input': as_raw(self.input_property_name)} - - def __evaluate__(self, container_holder): - if not isinstance(container_holder, Parameter): - raise CannotEvaluateFunctionException() - - service = container_holder.service - if service is None: - raise CannotEvaluateFunctionException() - - the_input = service.inputs.get(self.input_property_name) - if the_input is not None: - the_input = as_raw(the_input.value) - return Evaluation(the_input, False) - - -@dsl_specification('4.4.2', 'tosca-simple-1.0') -class GetProperty(Function): - """ - The :code:`get_property` function is used to retrieve property values between modelable entities - defined in the same service template. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if (not isinstance(argument, list)) or (len(argument) < 2): - raise InvalidValueError( - 'function "get_property" argument must be a list of at least 2 string expressions: ' - '{0}'.format(safe_repr(argument)), - locator=self.locator) - - self.modelable_entity_name = parse_modelable_entity_name(context, presentation, - 'get_property', 0, argument[0]) - # The first of these will be tried as a req-or-cap name: - self.nested_property_name_or_index = argument[1:] - - @property - def as_raw(self): - return {'get_property': [self.modelable_entity_name] + self.nested_property_name_or_index} - - def __evaluate__(self, container_holder): - context = ConsumptionContext.get_thread_local() - modelable_entities = get_modelable_entities(context, container_holder, self.locator, - self.modelable_entity_name) - req_or_cap_name = self.nested_property_name_or_index[0] - - for modelable_entity in modelable_entities: - properties = None - - if hasattr(modelable_entity, 'requirement_templates') \ - and modelable_entity.requirement_templates \ - and (req_or_cap_name in [v.name for v in modelable_entity.requirement_templates]): - for requirement_template in modelable_entity.requirement_templates: - if requirement_template.name == req_or_cap_name: - # First argument refers to a requirement - # TODO: should follow to matched capability in other node... - raise CannotEvaluateFunctionException() - break - nested_property_name_or_index = self.nested_property_name_or_index[1:] - elif hasattr(modelable_entity, 'capability_templates') \ - and modelable_entity.capability_templates \ - and (req_or_cap_name in modelable_entity.capability_templates): - # First argument refers to a capability - properties = modelable_entity.capability_templates[req_or_cap_name].properties - nested_property_name_or_index = self.nested_property_name_or_index[1:] - else: - properties = modelable_entity.properties - nested_property_name_or_index = self.nested_property_name_or_index - - evaluation = get_modelable_entity_parameter(context, modelable_entity, properties, - nested_property_name_or_index) - if evaluation is not None: - return evaluation - - raise InvalidValueError( - 'function "get_property" could not find "{0}" in modelable entity "{1}"' - .format('.'.join(self.nested_property_name_or_index), self.modelable_entity_name), - locator=self.locator) - - -# -# Attribute -# - -@dsl_specification('4.5.1', 'tosca-simple-1.0') -class GetAttribute(Function): - """ - The :code:`get_attribute` function is used to retrieve the values of named attributes declared - by the referenced node or relationship template name. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if (not isinstance(argument, list)) or (len(argument) < 2): - raise InvalidValueError( - 'function "get_attribute" argument must be a list of at least 2 string expressions:' - ' {0}'.format(safe_repr(argument)), - locator=self.locator) - - self.modelable_entity_name = parse_modelable_entity_name(context, presentation, - 'get_attribute', 0, argument[0]) - # The first of these will be tried as a req-or-cap name: - self.nested_attribute_name_or_index = argument[1:] - - @property - def as_raw(self): - return {'get_attribute': [self.modelable_entity_name] + self.nested_attribute_name_or_index} - - def __evaluate__(self, container_holder): - modelable_entities = get_modelable_entities(container_holder, self.locator, - self.modelable_entity_name) - for modelable_entity in modelable_entities: - attributes = modelable_entity.attributes - nested_attribute_name_or_index = self.nested_attribute_name_or_index - evaluation = get_modelable_entity_parameter(modelable_entity, attributes, - nested_attribute_name_or_index) - if evaluation is not None: - evaluation.final = False # We never return final evaluations! - return evaluation - - raise InvalidValueError( - 'function "get_attribute" could not find "{0}" in modelable entity "{1}"' - .format('.'.join(self.nested_attribute_name_or_index), self.modelable_entity_name), - locator=self.locator) - - -# -# Operation -# - -@dsl_specification('4.6.1', 'tosca-simple-1.0') -class GetOperationOutput(Function): - """ - The :code:`get_operation_output` function is used to retrieve the values of variables exposed / - exported from an interface operation. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if (not isinstance(argument, list)) or (len(argument) != 4): - raise InvalidValueError( - 'function "get_operation_output" argument must be a list of 4 parameters: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - self.modelable_entity_name = parse_string_expression(context, presentation, - 'get_operation_output', 0, - 'modelable entity name', argument[0]) - self.interface_name = parse_string_expression(context, presentation, 'get_operation_output', - 1, 'the interface name', argument[1]) - self.operation_name = parse_string_expression(context, presentation, 'get_operation_output', - 2, 'the operation name', argument[2]) - self.output_variable_name = parse_string_expression(context, presentation, - 'get_operation_output', 3, - 'the output name', argument[3]) - - @property - def as_raw(self): - interface_name = self.interface_name - if hasattr(interface_name, 'as_raw'): - interface_name = as_raw(interface_name) - operation_name = self.operation_name - if hasattr(operation_name, 'as_raw'): - operation_name = as_raw(operation_name) - output_variable_name = self.output_variable_name - if hasattr(output_variable_name, 'as_raw'): - output_variable_name = as_raw(output_variable_name) - return {'get_operation_output': [self.modelable_entity_name, interface_name, operation_name, - output_variable_name]} - - -# -# Navigation -# - -@dsl_specification('4.7.1', 'tosca-simple-1.0') -class GetNodesOfType(Function): - """ - The :code:`get_nodes_of_type` function can be used to retrieve a list of all known instances of - nodes of the declared Node Type. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - self.node_type_name = parse_string_expression(context, presentation, 'get_nodes_of_type', - None, 'the node type name', argument) - - if isinstance(self.node_type_name, basestring): - node_types = context.presentation.get('service_template', 'node_types') - if (node_types is None) or (self.node_type_name not in node_types): - raise InvalidValueError( - 'function "get_nodes_of_type" argument is not a valid node type name: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - @property - def as_raw(self): - node_type_name = self.node_type_name - if hasattr(node_type_name, 'as_raw'): - node_type_name = as_raw(node_type_name) - return {'get_nodes_of_type': node_type_name} - - def __evaluate__(self, container): - pass - - -# -# Artifact -# - -@dsl_specification('4.8.1', 'tosca-simple-1.0') -class GetArtifact(Function): - """ - The :code:`get_artifact` function is used to retrieve artifact location between modelable - entities defined in the same service template. - """ - - def __init__(self, context, presentation, argument): - self.locator = presentation._locator - - if (not isinstance(argument, list)) or (len(argument) < 2) or (len(argument) > 4): - raise InvalidValueError( - 'function "get_artifact" argument must be a list of 2 to 4 parameters: {0}' - .format(safe_repr(argument)), - locator=self.locator) - - self.modelable_entity_name = parse_string_expression(context, presentation, 'get_artifact', - 0, 'modelable entity name', - argument[0]) - self.artifact_name = parse_string_expression(context, presentation, 'get_artifact', 1, - 'the artifact name', argument[1]) - self.location = parse_string_expression(context, presentation, 'get_artifact', 2, - 'the location or "LOCAL_FILE"', argument[2]) - self.remove = parse_bool(context, presentation, 'get_artifact', 3, 'the removal flag', - argument[3]) - - @property - def as_raw(self): - artifact_name = self.artifact_name - if hasattr(artifact_name, 'as_raw'): - artifact_name = as_raw(artifact_name) - location = self.location - if hasattr(location, 'as_raw'): - location = as_raw(location) - return {'get_artifacts': [self.modelable_entity_name, artifact_name, location, self.remove]} - - -# -# Utils -# - -def get_function(context, presentation, value): - functions = context.presentation.presenter.functions - if isinstance(value, dict) and (len(value) == 1): - key = value.keys()[0] - if key in functions: - try: - return True, functions[key](context, presentation, value[key]) - except InvalidValueError as e: - context.validation.report(issue=e.issue) - return True, None - return False, None - - -def parse_string_expression(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument - is_function, func = get_function(context, presentation, value) - if is_function: - return func - else: - value = str(value) - return value - - -def parse_int(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument - if not isinstance(value, int): - try: - value = int(value) - except ValueError: - raise invalid_value(name, index, 'an integer', explanation, value, - presentation._locator) - return value - - -def parse_bool(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument - if not isinstance(value, bool): - raise invalid_value(name, index, 'a boolean', explanation, value, presentation._locator) - return value - - -def parse_modelable_entity_name(context, presentation, name, index, value): - value = parse_string_expression(context, presentation, name, index, 'the modelable entity name', - value) - if value == 'SELF': - the_self, _ = parse_self(presentation) - if the_self is None: - raise invalid_modelable_entity_name(name, index, value, presentation._locator, - 'a node template or a relationship template') - elif value == 'HOST': - _, self_variant = parse_self(presentation) - if self_variant != 'node_template': - raise invalid_modelable_entity_name(name, index, value, presentation._locator, - 'a node template') - elif (value == 'SOURCE') or (value == 'TARGET'): - _, self_variant = parse_self(presentation) - if self_variant != 'relationship_template': - raise invalid_modelable_entity_name(name, index, value, presentation._locator, - 'a relationship template') - elif isinstance(value, basestring): - node_templates = \ - context.presentation.get('service_template', 'topology_template', 'node_templates') \ - or {} - relationship_templates = \ - context.presentation.get('service_template', 'topology_template', - 'relationship_templates') \ - or {} - if (value not in node_templates) and (value not in relationship_templates): - raise InvalidValueError( - 'function "{0}" parameter {1:d} is not a valid modelable entity name: {2}' - .format(name, index + 1, safe_repr(value)), - locator=presentation._locator, level=Issue.BETWEEN_TYPES) - return value - - -def parse_self(presentation): - from .templates import NodeTemplate, RelationshipTemplate - from .types import NodeType, RelationshipType - - if presentation is None: - return None, None - elif isinstance(presentation, NodeTemplate) or isinstance(presentation, NodeType): - return presentation, 'node_template' - elif isinstance(presentation, RelationshipTemplate) \ - or isinstance(presentation, RelationshipType): - return presentation, 'relationship_template' - else: - return parse_self(presentation._container) - - -@dsl_specification('4.1', 'tosca-simple-1.0') -def get_modelable_entities(container_holder, locator, modelable_entity_name): - """ - The following keywords MAY be used in some TOSCA function in place of a TOSCA Node or - Relationship Template name. - """ - - if modelable_entity_name == 'SELF': - return get_self(container_holder) - elif modelable_entity_name == 'HOST': - return get_hosts(container_holder) - elif modelable_entity_name == 'SOURCE': - return get_source(container_holder) - elif modelable_entity_name == 'TARGET': - return get_target(container_holder) - elif isinstance(modelable_entity_name, basestring): - node_templates = \ - context.presentation.get('service_template', 'topology_template', 'node_templates') \ - or {} - if modelable_entity_name in node_templates: - return [node_templates[modelable_entity_name]] - relationship_templates = \ - context.presentation.get('service_template', 'topology_template', - 'relationship_templates') \ - or {} - if modelable_entity_name in relationship_templates: - return [relationship_templates[modelable_entity_name]] - - raise InvalidValueError('function "get_property" could not find modelable entity "{0}"' - .format(modelable_entity_name), - locator=locator) - - -def get_self(container_holder): - """ - A TOSCA orchestrator will interpret this keyword as the Node or Relationship Template instance - that contains the function at the time the function is evaluated. - """ - - return [container_holder.container] - - -def get_hosts(container_holder): # pylint: disable=unused-argument - """ - A TOSCA orchestrator will interpret this keyword to refer to the all nodes that "host" the node - using this reference (i.e., as identified by its HostedOn relationship). - - Specifically, TOSCA orchestrators that encounter this keyword when evaluating the get_attribute - or :code:`get_property` functions SHALL search each node along the "HostedOn" relationship chain - starting at the immediate node that hosts the node where the function was evaluated (and then - that node's host node, and so forth) until a match is found or the "HostedOn" relationship chain - ends. - """ - - return [] - - -def get_source(container_holder): # pylint: disable=unused-argument - """ - A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the - source end of the relationship that contains the referencing function. - """ - - return [] - - -def get_target(container_holder): # pylint: disable=unused-argument - """ - A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the - target end of the relationship that contains the referencing function. - """ - - -def get_modelable_entity_parameter(modelable_entity, parameters, nested_parameter_name_or_index): - if not parameters: - return False, True, None - - found = True - final = True - value = parameters - - for name in nested_parameter_name_or_index: - if (isinstance(value, dict) and (name in value)) \ - or (isinstance(value, list) and name < len(list)): - value = value[name].value - if hasattr(value, '__evaluate__'): - evaluation = value.__evaluate__(modelable_entity) - value = evaluation.value - if not evaluation.final: - final = False - else: - found = False - break - - return Evaluation(value, final) if found else None - - -def invalid_modelable_entity_name(name, index, value, locator, contexts): - return InvalidValueError('function "{0}" parameter {1:d} can be "{2}" only in {3}' - .format(name, index + 1, value, contexts), - locator=locator, level=Issue.FIELD) - - -def invalid_value(name, index, the_type, explanation, value, locator): - return InvalidValueError( - 'function "{0}" {1} is not {2}{3}: {4}' - .format(name, - 'parameter {0:d}'.format(index + 1) if index is not None else 'argument', - the_type, - ', {0}'.format(explanation) if explanation is not None else '', - safe_repr(value)), - locator=locator, level=Issue.FIELD) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/modeling/__init__.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/modeling/__init__.py b/extensions/aria_extension_tosca/simple_v1_0/modeling/__init__.py index c7e1a58..9c830d9 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/modeling/__init__.py +++ b/extensions/aria_extension_tosca/simple_v1_0/modeling/__init__.py @@ -32,6 +32,8 @@ from aria.modeling.models import (Type, ServiceTemplate, NodeTemplate, SubstitutionTemplateMapping, InterfaceTemplate, OperationTemplate, ArtifactTemplate, Metadata, Parameter, PluginSpecification) +from .constraints import (Equal, GreaterThan, GreaterOrEqual, LessThan, LessOrEqual, InRange, + ValidValues, Length, MinLength, MaxLength, Pattern) from ..data_types import coerce_value @@ -181,9 +183,9 @@ def create_node_template_model(context, service_template, node_template): model.capability_templates[capability_name] = \ create_capability_template_model(context, service_template, capability) - if model.target_node_template_constraints: + if node_template.node_filter: model.target_node_template_constraints = [] - create_node_filter_constraint_lambdas(context, node_template.node_filter, + create_node_filter_constraint_filters(context, node_template.node_filter, model.target_node_template_constraints) return model @@ -273,9 +275,9 @@ def create_requirement_template_model(context, service_template, requirement): model = RequirementTemplate(**model) - if model.target_node_template_constraints: + if requirement.node_filter: model.target_node_template_constraints = [] - create_node_filter_constraint_lambdas(context, requirement.node_filter, + create_node_filter_constraint_filters(context, requirement.node_filter, model.target_node_template_constraints) relationship = requirement.relationship @@ -559,14 +561,11 @@ def create_interface_template_models(context, service_template, interfaces, sour interfaces[interface_name] = interface -def create_node_filter_constraint_lambdas(context, node_filter, target_node_template_constraints): - if node_filter is None: - return - +def create_node_filter_constraint_filters(context, node_filter, target_node_template_constraints): properties = node_filter.properties if properties is not None: for property_name, constraint_clause in properties: - func = create_constraint_clause_lambda(context, node_filter, constraint_clause, + func = create_constraint_clause_filter(context, node_filter, constraint_clause, property_name, None) if func is not None: target_node_template_constraints.append(func) @@ -577,129 +576,65 @@ def create_node_filter_constraint_lambdas(context, node_filter, target_node_temp properties = capability.properties if properties is not None: for property_name, constraint_clause in properties: - func = create_constraint_clause_lambda(context, node_filter, constraint_clause, + func = create_constraint_clause_filter(context, node_filter, constraint_clause, property_name, capability_name) if func is not None: target_node_template_constraints.append(func) -def create_constraint_clause_lambda(context, node_filter, constraint_clause, property_name, # pylint: disable=too-many-return-statements +def create_constraint_clause_filter(context, node_filter, constraint_clause, property_name, # pylint: disable=too-many-return-statements capability_name): constraint_key = constraint_clause._raw.keys()[0] - the_type = constraint_clause._get_type(context) - def coerce_constraint(constraint, container): - constraint = coerce_value(context, node_filter, the_type, None, None, constraint, - constraint_key) if the_type is not None else constraint - if hasattr(constraint, '__evaluate__'): - constraint = constraint.__evaluate__(container).value - return constraint - - def get_value(node_type): - if capability_name is not None: - capability = node_type.capability_templates.get(capability_name) - prop = capability.properties.get(property_name) if capability is not None else None - return prop.value if prop is not None else None - value = node_type.properties.get(property_name) - return value.value if value is not None else None + the_type = constraint_clause._get_type(context) - if constraint_key == 'equal': - def equal(node_type, container): - constraint = coerce_constraint(constraint_clause.equal, container) - value = get_value(node_type) - return value == constraint + def coerce_constraint(constraint): + if the_type is not None: + return coerce_value(context, node_filter, the_type, None, None, constraint, constraint_key) + else: + return constraint - return equal + def coerce_constraints(constraints): + if the_type is not None: + return tuple(coerce_constraint(constraint) for constraint in constraints) + else: + return constraints + if constraint_key == 'equal': + return Equal(property_name, capability_name, + coerce_constraint(constraint_clause.equal)) elif constraint_key == 'greater_than': - def greater_than(node_type, container): - constraint = coerce_constraint(constraint_clause.greater_than, container) - value = get_value(node_type) - return value > constraint - - return greater_than - + return GreaterThan(property_name, capability_name, + coerce_constraint(constraint_clause.greater_than)) elif constraint_key == 'greater_or_equal': - def greater_or_equal(node_type, container): - constraint = coerce_constraint(constraint_clause.greater_or_equal, container) - value = get_value(node_type) - return value >= constraint - - return greater_or_equal - + return GreaterOrEqual(property_name, capability_name, + coerce_constraint(constraint_clause.greater_or_equal)) elif constraint_key == 'less_than': - def less_than(node_type, container): - constraint = coerce_constraint(constraint_clause.less_than, container) - value = get_value(node_type) - return value < constraint - - return less_than - + return LessThan(property_name, capability_name, + coerce_constraint(constraint_clause.less_than)) elif constraint_key == 'less_or_equal': - def less_or_equal(node_type, container): - constraint = coerce_constraint(constraint_clause.less_or_equal, container) - value = get_value(node_type) - return value <= constraint - - return less_or_equal - + return LessOrEqual(property_name, capability_name, + coerce_constraint(constraint_clause.less_or_equal)) elif constraint_key == 'in_range': - def in_range(node_type, container): - lower, upper = constraint_clause.in_range - lower, upper = coerce_constraint(lower, container), coerce_constraint(upper, container) - value = get_value(node_type) - if value < lower: - return False - if (upper != 'UNBOUNDED') and (value > upper): - return False - return True - - return in_range - + return InRange(property_name, capability_name, + coerce_constraints(constraint_clause.in_range), plural=True) elif constraint_key == 'valid_values': - def valid_values(node_type, container): - constraint = tuple(coerce_constraint(v, container) - for v in constraint_clause.valid_values) - value = get_value(node_type) - return value in constraint - - return valid_values - + return ValidValues(property_name, capability_name, + coerce_constraints(constraint_clause.valid_values), plural=True) elif constraint_key == 'length': - def length(node_type, container): # pylint: disable=unused-argument - constraint = constraint_clause.length - value = get_value(node_type) - return len(value) == constraint - - return length - + return Length(property_name, capability_name, + coerce_constraint(constraint_clause.length)) elif constraint_key == 'min_length': - def min_length(node_type, container): # pylint: disable=unused-argument - constraint = constraint_clause.min_length - value = get_value(node_type) - return len(value) >= constraint - - return min_length - + return MinLength(property_name, capability_name, + coerce_constraint(constraint_clause.min_length)) elif constraint_key == 'max_length': - def max_length(node_type, container): # pylint: disable=unused-argument - constraint = constraint_clause.max_length - value = get_value(node_type) - return len(value) >= constraint - - return max_length - + return MaxLength(property_name, capability_name, + coerce_constraint(constraint_clause.max_length)) elif constraint_key == 'pattern': - def pattern(node_type, container): # pylint: disable=unused-argument - constraint = constraint_clause.pattern - # Note: the TOSCA 1.0 spec does not specify the regular expression grammar, so we will - # just use Python's - value = node_type.properties.get(property_name) - return re.match(constraint, str(value)) is not None - - return pattern - - return None + return Pattern(property_name, capability_name, + coerce_constraint(constraint_clause.pattern)) + else: + raise ValueError('malformed node_filter: {0}'.format(constraint_key)) def split_prefix(string): http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/modeling/data_types.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/modeling/data_types.py b/extensions/aria_extension_tosca/simple_v1_0/modeling/data_types.py index 8bf45e0..01f222f 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/modeling/data_types.py +++ b/extensions/aria_extension_tosca/simple_v1_0/modeling/data_types.py @@ -22,7 +22,7 @@ from aria.parser import dsl_specification from aria.parser.presentation import (get_locator, validate_primitive) from aria.parser.validation import Issue -from ..functions import get_function +from .functions import get_function from ..presentation.types import get_type_by_full_or_shorthand_name # http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py b/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py new file mode 100644 index 0000000..ba6cafd --- /dev/null +++ b/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py @@ -0,0 +1,687 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from cStringIO import StringIO +import re + +from aria.utils.collections import FrozenList +from aria.utils.formatting import as_raw, safe_repr, full_type_name +from aria.parser import dsl_specification +from aria.parser.exceptions import InvalidValueError +from aria.parser.validation import Issue +from aria.modeling.exceptions import CannotEvaluateFunctionException +from aria.modeling.models import (Parameter, Node, NodeTemplate, Relationship, RelationshipTemplate) +from aria.modeling.functions import (Function, Evaluation) + + +# +# Intrinsic +# + +@dsl_specification('4.3.1', 'tosca-simple-1.0') +class Concat(Function): + """ + The :code:`concat` function is used to concatenate two or more string values within a TOSCA + service template. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if not isinstance(argument, list): + raise InvalidValueError( + 'function "concat" argument must be a list of string expressions: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + string_expressions = [] + for index, an_argument in enumerate(argument): + string_expressions.append(parse_string_expression(context, presentation, 'concat', + index, None, an_argument)) + self.string_expressions = FrozenList(string_expressions) + + @property + def as_raw(self): + string_expressions = [] + for string_expression in self.string_expressions: + if hasattr(string_expression, 'as_raw'): + string_expression = as_raw(string_expression) + string_expressions.append(string_expression) + return {'concat': string_expressions} + + def __evaluate__(self, container_holder): + final = True + value = StringIO() + for e in self.string_expressions: + e, final = evaluate(e, final, container_holder) + if e is not None: + value.write(unicode(e)) + value = value.getvalue() + return Evaluation(value, final) + + +@dsl_specification('4.3.2', 'tosca-simple-1.0') +class Token(Function): + """ + The :code:`token` function is used within a TOSCA service template on a string to parse out + (tokenize) substrings separated by one or more token characters within a larger string. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if (not isinstance(argument, list)) or (len(argument) != 3): + raise InvalidValueError('function "token" argument must be a list of 3 parameters: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + self.string_with_tokens = parse_string_expression(context, presentation, 'token', 0, + 'the string to tokenize', argument[0]) + self.string_of_token_chars = parse_string_expression(context, presentation, 'token', 1, + 'the token separator characters', + argument[1]) + self.substring_index = parse_int(context, presentation, 'token', 2, + 'the 0-based index of the token to return', argument[2]) + + @property + def as_raw(self): + string_with_tokens = self.string_with_tokens + if hasattr(string_with_tokens, 'as_raw'): + string_with_tokens = as_raw(string_with_tokens) + string_of_token_chars = self.string_of_token_chars + if hasattr(string_of_token_chars, 'as_raw'): + string_of_token_chars = as_raw(string_of_token_chars) + return {'token': [string_with_tokens, string_of_token_chars, self.substring_index]} + + def __evaluate__(self, container_holder): + final = True + string_with_tokens, final = evaluate(self.string_with_tokens, final, container_holder) + string_of_token_chars, final = evaluate(self.string_of_token_chars, final, container_holder) + + if string_of_token_chars: + regex = '[' + ''.join(re.escape(c) for c in string_of_token_chars) + ']' + split = re.split(regex, string_with_tokens) + if self.substring_index < len(split): + return Evaluation(split[self.substring_index], final) + + raise CannotEvaluateFunctionException() + + +# +# Property +# + +@dsl_specification('4.4.1', 'tosca-simple-1.0') +class GetInput(Function): + """ + The :code:`get_input` function is used to retrieve the values of properties declared within the + inputs section of a TOSCA Service Template. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + self.input_property_name = parse_string_expression(context, presentation, 'get_input', + None, 'the input property name', + argument) + + if isinstance(self.input_property_name, basestring): + the_input = context.presentation.get_from_dict('service_template', 'topology_template', + 'inputs', self.input_property_name) + if the_input is None: + raise InvalidValueError( + 'function "get_input" argument is not a valid input name: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + @property + def as_raw(self): + return {'get_input': as_raw(self.input_property_name)} + + def __evaluate__(self, container_holder): + if not isinstance(container_holder, Parameter): + raise CannotEvaluateFunctionException() + + service = container_holder.service + if service is None: + raise CannotEvaluateFunctionException() + + value = service.inputs.get(self.input_property_name) + if value is None: + raise InvalidValueError( + 'function "get_input" argument is not a valid input name: {0}' + .format(safe_repr(self.input_property_name)), + locator=self.locator) + + value = value.value + value, _ = evaluate(value, False, container_holder) + #value = as_raw(value) + return Evaluation(value, False) # We never return final evaluations! + + +@dsl_specification('4.4.2', 'tosca-simple-1.0') +class GetProperty(Function): + """ + The :code:`get_property` function is used to retrieve property values between modelable entities + defined in the same service template. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if (not isinstance(argument, list)) or (len(argument) < 2): + raise InvalidValueError( + 'function "get_property" argument must be a list of at least 2 string expressions: ' + '{0}'.format(safe_repr(argument)), + locator=self.locator) + + self.modelable_entity_name = parse_modelable_entity_name(context, presentation, + 'get_property', 0, argument[0]) + # The first of these will be tried as a req-or-cap name: + self.nested_property_name_or_index = argument[1:] + + @property + def as_raw(self): + return {'get_property': [self.modelable_entity_name] + self.nested_property_name_or_index} + + def __evaluate__(self, container_holder): + modelable_entities = get_modelable_entities(container_holder, 'get_property', self.locator, + self.modelable_entity_name) + req_or_cap_name = self.nested_property_name_or_index[0] + + for modelable_entity in modelable_entities: + properties = None + + if hasattr(modelable_entity, 'requirement_templates') \ + and modelable_entity.requirement_templates \ + and (req_or_cap_name in [v.name for v in modelable_entity.requirement_templates]): + for requirement_template in modelable_entity.requirement_templates: + if requirement_template.name == req_or_cap_name: + # First argument refers to a requirement + # TODO: should follow to matched capability in other node... + raise CannotEvaluateFunctionException() + break + nested_property_name_or_index = self.nested_property_name_or_index[1:] + elif hasattr(modelable_entity, 'capability_templates') \ + and modelable_entity.capability_templates \ + and (req_or_cap_name in modelable_entity.capability_templates): + # First argument refers to a capability + properties = modelable_entity.capability_templates[req_or_cap_name].properties + nested_property_name_or_index = self.nested_property_name_or_index[1:] + else: + properties = modelable_entity.properties + nested_property_name_or_index = self.nested_property_name_or_index + + evaluation = get_modelable_entity_parameter(modelable_entity, properties, + nested_property_name_or_index) + if evaluation is not None: + return evaluation + + raise InvalidValueError( + 'function "get_property" could not find "{0}" in modelable entity "{1}"' + .format('.'.join(self.nested_property_name_or_index), self.modelable_entity_name), + locator=self.locator) + + +# +# Attribute +# + +@dsl_specification('4.5.1', 'tosca-simple-1.0') +class GetAttribute(Function): + """ + The :code:`get_attribute` function is used to retrieve the values of named attributes declared + by the referenced node or relationship template name. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if (not isinstance(argument, list)) or (len(argument) < 2): + raise InvalidValueError( + 'function "get_attribute" argument must be a list of at least 2 string expressions:' + ' {0}'.format(safe_repr(argument)), + locator=self.locator) + + self.modelable_entity_name = parse_modelable_entity_name(context, presentation, + 'get_attribute', 0, argument[0]) + # The first of these will be tried as a req-or-cap name: + self.nested_attribute_name_or_index = argument[1:] + + @property + def as_raw(self): + return {'get_attribute': [self.modelable_entity_name] + self.nested_attribute_name_or_index} + + def __evaluate__(self, container_holder): + modelable_entities = get_modelable_entities(container_holder, 'get_attribute', self.locator, + self.modelable_entity_name) + for modelable_entity in modelable_entities: + attributes = modelable_entity.attributes + nested_attribute_name_or_index = self.nested_attribute_name_or_index + evaluation = get_modelable_entity_parameter(modelable_entity, attributes, + nested_attribute_name_or_index) + if evaluation is not None: + evaluation.final = False # We never return final evaluations! + return evaluation + + raise InvalidValueError( + 'function "get_attribute" could not find "{0}" in modelable entity "{1}"' + .format('.'.join(self.nested_attribute_name_or_index), self.modelable_entity_name), + locator=self.locator) + + +# +# Operation +# + +@dsl_specification('4.6.1', 'tosca-simple-1.0') +class GetOperationOutput(Function): + """ + The :code:`get_operation_output` function is used to retrieve the values of variables exposed / + exported from an interface operation. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if (not isinstance(argument, list)) or (len(argument) != 4): + raise InvalidValueError( + 'function "get_operation_output" argument must be a list of 4 parameters: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + self.modelable_entity_name = parse_string_expression(context, presentation, + 'get_operation_output', 0, + 'modelable entity name', argument[0]) + self.interface_name = parse_string_expression(context, presentation, 'get_operation_output', + 1, 'the interface name', argument[1]) + self.operation_name = parse_string_expression(context, presentation, 'get_operation_output', + 2, 'the operation name', argument[2]) + self.output_variable_name = parse_string_expression(context, presentation, + 'get_operation_output', 3, + 'the output name', argument[3]) + + @property + def as_raw(self): + interface_name = self.interface_name + if hasattr(interface_name, 'as_raw'): + interface_name = as_raw(interface_name) + operation_name = self.operation_name + if hasattr(operation_name, 'as_raw'): + operation_name = as_raw(operation_name) + output_variable_name = self.output_variable_name + if hasattr(output_variable_name, 'as_raw'): + output_variable_name = as_raw(output_variable_name) + return {'get_operation_output': [self.modelable_entity_name, interface_name, operation_name, + output_variable_name]} + + +# +# Navigation +# + +@dsl_specification('4.7.1', 'tosca-simple-1.0') +class GetNodesOfType(Function): + """ + The :code:`get_nodes_of_type` function can be used to retrieve a list of all known instances of + nodes of the declared Node Type. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + self.node_type_name = parse_string_expression(context, presentation, 'get_nodes_of_type', + None, 'the node type name', argument) + + if isinstance(self.node_type_name, basestring): + node_types = context.presentation.get('service_template', 'node_types') + if (node_types is None) or (self.node_type_name not in node_types): + raise InvalidValueError( + 'function "get_nodes_of_type" argument is not a valid node type name: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + @property + def as_raw(self): + node_type_name = self.node_type_name + if hasattr(node_type_name, 'as_raw'): + node_type_name = as_raw(node_type_name) + return {'get_nodes_of_type': node_type_name} + + def __evaluate__(self, container): + pass + + +# +# Artifact +# + +@dsl_specification('4.8.1', 'tosca-simple-1.0') +class GetArtifact(Function): + """ + The :code:`get_artifact` function is used to retrieve artifact location between modelable + entities defined in the same service template. + """ + + def __init__(self, context, presentation, argument): + self.locator = presentation._locator + + if (not isinstance(argument, list)) or (len(argument) < 2) or (len(argument) > 4): + raise InvalidValueError( + 'function "get_artifact" argument must be a list of 2 to 4 parameters: {0}' + .format(safe_repr(argument)), + locator=self.locator) + + self.modelable_entity_name = parse_string_expression(context, presentation, 'get_artifact', + 0, 'modelable entity name', + argument[0]) + self.artifact_name = parse_string_expression(context, presentation, 'get_artifact', 1, + 'the artifact name', argument[1]) + self.location = parse_string_expression(context, presentation, 'get_artifact', 2, + 'the location or "LOCAL_FILE"', argument[2]) + self.remove = parse_bool(context, presentation, 'get_artifact', 3, 'the removal flag', + argument[3]) + + @property + def as_raw(self): + artifact_name = self.artifact_name + if hasattr(artifact_name, 'as_raw'): + artifact_name = as_raw(artifact_name) + location = self.location + if hasattr(location, 'as_raw'): + location = as_raw(location) + return {'get_artifacts': [self.modelable_entity_name, artifact_name, location, self.remove]} + + +# +# Utils +# + +def get_function(context, presentation, value): + functions = context.presentation.presenter.functions + if isinstance(value, dict) and (len(value) == 1): + key = value.keys()[0] + if key in functions: + try: + return True, functions[key](context, presentation, value[key]) + except InvalidValueError as e: + context.validation.report(issue=e.issue) + return True, None + return False, None + + +def parse_string_expression(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument + is_function, func = get_function(context, presentation, value) + if is_function: + return func + else: + value = str(value) + return value + + +def parse_int(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument + if not isinstance(value, int): + try: + value = int(value) + except ValueError: + raise invalid_value(name, index, 'an integer', explanation, value, + presentation._locator) + return value + + +def parse_bool(context, presentation, name, index, explanation, value): # pylint: disable=unused-argument + if not isinstance(value, bool): + raise invalid_value(name, index, 'a boolean', explanation, value, presentation._locator) + return value + + +def parse_modelable_entity_name(context, presentation, name, index, value): + value = parse_string_expression(context, presentation, name, index, 'the modelable entity name', + value) + if value == 'SELF': + the_self, _ = parse_self(presentation) + if the_self is None: + raise invalid_modelable_entity_name(name, index, value, presentation._locator, + 'a node template or a relationship template') + elif value == 'HOST': + _, self_variant = parse_self(presentation) + if self_variant != 'node_template': + raise invalid_modelable_entity_name(name, index, value, presentation._locator, + 'a node template') + elif (value == 'SOURCE') or (value == 'TARGET'): + _, self_variant = parse_self(presentation) + if self_variant != 'relationship_template': + raise invalid_modelable_entity_name(name, index, value, presentation._locator, + 'a relationship template') + elif isinstance(value, basestring): + node_templates = \ + context.presentation.get('service_template', 'topology_template', 'node_templates') \ + or {} + relationship_templates = \ + context.presentation.get('service_template', 'topology_template', + 'relationship_templates') \ + or {} + if (value not in node_templates) and (value not in relationship_templates): + raise InvalidValueError( + 'function "{0}" parameter {1:d} is not a valid modelable entity name: {2}' + .format(name, index + 1, safe_repr(value)), + locator=presentation._locator, level=Issue.BETWEEN_TYPES) + return value + + +def parse_self(presentation): + from ..types import (NodeType, RelationshipType) + from ..templates import ( + NodeTemplate as NodeTemplatePresentation, + RelationshipTemplate as RelationshipTemplatePresentation + ) + + if presentation is None: + return None, None + elif isinstance(presentation, NodeTemplatePresentation) or isinstance(presentation, NodeType): + return presentation, 'node_template' + elif isinstance(presentation, RelationshipTemplatePresentation) \ + or isinstance(presentation, RelationshipType): + return presentation, 'relationship_template' + else: + return parse_self(presentation._container) + + +def evaluate(value, final, container_holder): + if hasattr(value, '__evaluate__'): + value = value.__evaluate__(container_holder) + if not value.final: + final = False + return value.value, final + else: + return value, final + + +@dsl_specification('4.1', 'tosca-simple-1.0') +def get_modelable_entities(container_holder, name, locator, modelable_entity_name): + """ + The following keywords MAY be used in some TOSCA function in place of a TOSCA Node or + Relationship Template name. + """ + + if modelable_entity_name == 'SELF': + return get_self(container_holder, name, locator) + elif modelable_entity_name == 'HOST': + return get_hosts(container_holder, name, locator) + elif modelable_entity_name == 'SOURCE': + return get_source(container_holder, name, locator) + elif modelable_entity_name == 'TARGET': + return get_target(container_holder, name, locator) + elif isinstance(modelable_entity_name, basestring): + modelable_entities = [] + + service = container_holder.service + if service is not None: + for node in service.nodes.itervalues(): + if node.node_template.name == modelable_entity_name: + modelable_entities.append(node) + else: + service_template = container_holder.service_template + if service_template is not None: + for node_template in service_template.node_templates.itervalues(): + if node_template.name == modelable_entity_name: + modelable_entities.append(node_template) + + if not modelable_entities: + raise CannotEvaluateFunctionException() + + return modelable_entities + + #node_templates = \ + # context.presentation.get('service_template', 'topology_template', 'node_templates') \ + # or {} + #if modelable_entity_name in node_templates: + # return [node_templates[modelable_entity_name]] + #relationship_templates = \ + # context.presentation.get('service_template', 'topology_template', + # 'relationship_templates') \ + # or {} + #if modelable_entity_name in relationship_templates: + # return [relationship_templates[modelable_entity_name]] + + raise InvalidValueError('function "{0}" could not find modelable entity "{0}"' + .format(name, modelable_entity_name), + locator=locator) + + +def get_self(container_holder, name, locator): + """ + A TOSCA orchestrator will interpret this keyword as the Node or Relationship Template instance + that contains the function at the time the function is evaluated. + """ + + container = container_holder.container + if (not isinstance(container, Node)) and \ + (not isinstance(container, NodeTemplate)) and \ + (not isinstance(container, Relationship)) and \ + (not isinstance(container, RelationshipTemplate)): + raise InvalidValueError('function "{0}" refers to "SELF" but it is not contained in ' + 'a node or a relationship: {1}'.format(name, + full_type_name(container)), + locator=locator) + + return [container] + + +def get_hosts(container_holder, name, locator): + """ + A TOSCA orchestrator will interpret this keyword to refer to the all nodes that "host" the node + using this reference (i.e., as identified by its HostedOn relationship). + + Specifically, TOSCA orchestrators that encounter this keyword when evaluating the get_attribute + or :code:`get_property` functions SHALL search each node along the "HostedOn" relationship chain + starting at the immediate node that hosts the node where the function was evaluated (and then + that node's host node, and so forth) until a match is found or the "HostedOn" relationship chain + ends. + """ + + container = container_holder.container + if (not isinstance(container, Node)) and (not isinstance(container, NodeTemplate)): + raise InvalidValueError('function "{0}" refers to "HOST" but it is not contained in ' + 'a node: {1}'.format(name, full_type_name(container)), + locator=locator) + + if not isinstance(container, Node): + # NodeTemplate does not have "host"; we'll wait until instantiation + raise CannotEvaluateFunctionException() + + host = container.host + if host is None: + # We might have a host later + raise CannotEvaluateFunctionException() + + return [host] + + +def get_source(container_holder, name, locator): + """ + A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the + source end of the relationship that contains the referencing function. + """ + + container = container_holder.container + if (not isinstance(container, Relationship)) and \ + (not isinstance(container, RelationshipTemplate)): + raise InvalidValueError('function "{0}" refers to "SOURCE" but it is not contained in ' + 'a relationship: {1}'.format(name, full_type_name(container)), + locator=locator) + + if not isinstance(container, RelationshipTemplate): + # RelationshipTemplate does not have "source_node"; we'll wait until instantiation + raise CannotEvaluateFunctionException() + + return [container.source_node] + + +def get_target(container_holder, name, locator): + """ + A TOSCA orchestrator will interpret this keyword as the Node Template instance that is at the + target end of the relationship that contains the referencing function. + """ + + container = container_holder.container + if (not isinstance(container, Relationship)) and \ + (not isinstance(container, RelationshipTemplate)): + raise InvalidValueError('function "{0}" refers to "TARGET" but it is not contained in ' + 'a relationship: {1}'.format(name, full_type_name(container)), + locator=locator) + + if not isinstance(container, RelationshipTemplate): + # RelationshipTemplate does not have "target_node"; we'll wait until instantiation + raise CannotEvaluateFunctionException() + + return [container.target_node] + + +def get_modelable_entity_parameter(modelable_entity, parameters, nested_parameter_name_or_index): + if not parameters: + return False, True, None + + found = True + final = True + value = parameters + + for name in nested_parameter_name_or_index: + if (isinstance(value, dict) and (name in value)) \ + or (isinstance(value, list) and name < len(list)): + value = value[name].value + value, final = evaluate(value, final, modelable_entity) + else: + found = False + break + + return Evaluation(value, final) if found else None + + +def invalid_modelable_entity_name(name, index, value, locator, contexts): + return InvalidValueError('function "{0}" parameter {1:d} can be "{2}" only in {3}' + .format(name, index + 1, value, contexts), + locator=locator, level=Issue.FIELD) + + +def invalid_value(name, index, the_type, explanation, value, locator): + return InvalidValueError( + 'function "{0}" {1} is not {2}{3}: {4}' + .format(name, + 'parameter {0:d}'.format(index + 1) if index is not None else 'argument', + the_type, + ', {0}'.format(explanation) if explanation is not None else '', + safe_repr(value)), + locator=locator, level=Issue.FIELD) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/extensions/aria_extension_tosca/simple_v1_0/presenter.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/presenter.py b/extensions/aria_extension_tosca/simple_v1_0/presenter.py index 96cc763..231a7d1 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/presenter.py +++ b/extensions/aria_extension_tosca/simple_v1_0/presenter.py @@ -17,9 +17,9 @@ from aria.utils.collections import FrozenList, EMPTY_READ_ONLY_LIST from aria.utils.caching import cachedmethod from aria.parser.presentation import Presenter -from .functions import (Concat, Token, GetInput, GetProperty, GetAttribute, GetOperationOutput, - GetNodesOfType, GetArtifact) from .modeling import create_service_template_model +from .modeling.functions import (Concat, Token, GetInput, GetProperty, GetAttribute, + GetOperationOutput, GetNodesOfType, GetArtifact) from .templates import ServiceTemplate class ToscaSimplePresenter1_0(Presenter): # pylint: disable=invalid-name http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c42bb403/tests/resources/service-templates/tosca-simple-1.0/node-cellar/node-cellar.yaml ---------------------------------------------------------------------- diff --git a/tests/resources/service-templates/tosca-simple-1.0/node-cellar/node-cellar.yaml b/tests/resources/service-templates/tosca-simple-1.0/node-cellar/node-cellar.yaml index cf2f874..8e80640 100644 --- a/tests/resources/service-templates/tosca-simple-1.0/node-cellar/node-cellar.yaml +++ b/tests/resources/service-templates/tosca-simple-1.0/node-cellar/node-cellar.yaml @@ -98,6 +98,8 @@ topology_template: token: { get_attribute: [ SELF, tosca_id ] } #token: { get_property: [ SELF, app_endpoint, protocol ] } #token: { get_property: [ HOST, flavor_name ] } + #token: { token: [ { get_property: [ HOST, flavor_name ] }, '.', 1 ] } + #token: { token: [ 'zero.one|two-three', '.|-', 3 ] } interfaces: Maintenance: enable: juju > charm.maintenance_on
