http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/b7e1836d/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 9576260..add0766 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 @@ -164,6 +166,8 @@ def create_node_template_model(context, service_template, node_template): create_parameter_models_from_values(model.properties, node_template._get_property_values(context)) + create_parameter_models_from_values(model.attributes, + node_template._get_attribute_default_values(context)) create_interface_template_models(context, service_template, model.interface_templates, node_template._get_interfaces(context)) @@ -179,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_constraints(context, node_template.node_filter, model.target_node_template_constraints) return model @@ -271,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_constraints(context, requirement.node_filter, model.target_node_template_constraints) relationship = requirement.relationship @@ -557,17 +561,13 @@ 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_constraints(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, - property_name, None) - if func is not None: - target_node_template_constraints.append(func) + constraint = create_constraint(context, node_filter, constraint_clause, property_name, + None) + target_node_template_constraints.append(constraint) capabilities = node_filter.capabilities if capabilities is not None: @@ -575,129 +575,64 @@ 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, - property_name, capability_name) - if func is not None: - target_node_template_constraints.append(func) + constraint = create_constraint(context, node_filter, constraint_clause, + property_name, capability_name) + target_node_template_constraints.append(constraint) -def create_constraint_clause_lambda(context, node_filter, constraint_clause, property_name, # pylint: disable=too-many-return-statements - capability_name): +def create_constraint(context, node_filter, constraint_clause, property_name, capability_name): # pylint: disable=too-many-return-statements 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(context, container) - 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)) 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)) 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/b7e1836d/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 99dcfea..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 # @@ -327,20 +327,20 @@ def get_data_type_value(context, presentation, field_name, type_name): PRIMITIVE_DATA_TYPES = { # YAML 1.2: - 'tag:yaml.org,2002:str': str, + 'tag:yaml.org,2002:str': unicode, 'tag:yaml.org,2002:integer': int, 'tag:yaml.org,2002:float': float, 'tag:yaml.org,2002:bool': bool, 'tag:yaml.org,2002:null': None.__class__, # TOSCA aliases: - 'string': str, + 'string': unicode, 'integer': int, 'float': float, 'boolean': bool, 'null': None.__class__} -@dsl_specification('3.2.1', 'tosca-simple-1.0') +@dsl_specification('3.2.1-1', 'tosca-simple-1.0') def get_primitive_data_type(type_name): """ Many of the types we use in this profile are built-in types from the YAML 1.2 specification @@ -371,6 +371,8 @@ def coerce_value(context, presentation, the_type, entry_schema, constraints, val If the extension is present, we will delegate to that hook. """ + # TODO: should support models as well as presentations + is_function, func = get_function(context, presentation, value) if is_function: return func http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/b7e1836d/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/b7e1836d/extensions/aria_extension_tosca/simple_v1_0/modeling/properties.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/modeling/properties.py b/extensions/aria_extension_tosca/simple_v1_0/modeling/properties.py index f61cb99..9c3ea42 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/modeling/properties.py +++ b/extensions/aria_extension_tosca/simple_v1_0/modeling/properties.py @@ -58,7 +58,8 @@ def get_inherited_property_definitions(context, presentation, field_name, for_pr # NodeTemplate, RelationshipTemplate, GroupTemplate, PolicyTemplate # -def get_assigned_and_defined_property_values(context, presentation): +def get_assigned_and_defined_property_values(context, presentation, field_name='property', + field_name_plural='properties'): """ Returns the assigned property values while making sure they are defined in our type. @@ -70,8 +71,9 @@ def get_assigned_and_defined_property_values(context, presentation): values = OrderedDict() the_type = presentation._get_type(context) - assignments = presentation.properties - definitions = the_type._get_properties(context) if the_type is not None else None + assignments = getattr(presentation, field_name_plural) + get_fn_name = '_get_{0}'.format(field_name_plural) + definitions = getattr(the_type, get_fn_name)(context) if the_type is not None else None # Fill in our assignments, but make sure they are defined if assignments: @@ -80,14 +82,14 @@ def get_assigned_and_defined_property_values(context, presentation): definition = definitions[name] values[name] = coerce_property_value(context, value, definition, value.value) else: - context.validation.report('assignment to undefined property "%s" in "%s"' - % (name, presentation._fullname), + context.validation.report('assignment to undefined {0} "{1}" in "{2}"' + .format(field_name, name, presentation._fullname), locator=value._locator, level=Issue.BETWEEN_TYPES) # Fill in defaults from the definitions if definitions: for name, definition in definitions.iteritems(): - if (values.get(name) is None) and (definition.default is not None): + if values.get(name) is None: values[name] = coerce_property_value(context, presentation, definition, definition.default) @@ -181,7 +183,8 @@ def merge_property_definitions(context, presentation, property_definitions, def coerce_property_value(context, presentation, definition, value, aspect=None): the_type = definition._get_type(context) if definition is not None else None entry_schema = definition.entry_schema if definition is not None else None - constraints = definition._get_constraints(context) if definition is not None else None + constraints = definition._get_constraints(context) \ + if ((definition is not None) and hasattr(definition, '_get_constraints')) else None value = coerce_value(context, presentation, the_type, entry_schema, constraints, value, aspect) if (the_type is not None) and hasattr(the_type, '_name'): type_name = the_type._name http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/b7e1836d/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/b7e1836d/extensions/aria_extension_tosca/simple_v1_0/templates.py ---------------------------------------------------------------------- diff --git a/extensions/aria_extension_tosca/simple_v1_0/templates.py b/extensions/aria_extension_tosca/simple_v1_0/templates.py index 6860b72..c0f9f23 100644 --- a/extensions/aria_extension_tosca/simple_v1_0/templates.py +++ b/extensions/aria_extension_tosca/simple_v1_0/templates.py @@ -26,7 +26,7 @@ from .assignments import (PropertyAssignment, AttributeAssignment, RequirementAs from .definitions import ParameterDefinition from .filters import NodeFilter from .misc import (Description, MetaData, Repository, Import, SubstitutionMappings) -from .modeling.properties import get_assigned_and_defined_property_values, get_parameter_values +from .modeling.properties import (get_assigned_and_defined_property_values, get_parameter_values) from .modeling.interfaces import get_template_interfaces from .modeling.requirements import get_template_requirements from .modeling.capabilities import get_template_capabilities @@ -160,6 +160,11 @@ class NodeTemplate(ExtensiblePresentation): return FrozenDict(get_assigned_and_defined_property_values(context, self)) @cachedmethod + def _get_attribute_default_values(self, context): + return FrozenDict(get_assigned_and_defined_property_values(context, self, + 'attribute', 'attributes')) + + @cachedmethod def _get_requirements(self, context): return FrozenList(get_template_requirements(context, self)) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/b7e1836d/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 349a166..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 @@ -33,6 +33,7 @@ imports: - types/mongodb.yaml - types/nginx.yaml - aria-1.0 + dsl_definitions: default_openstack_credential: &DEFAULT_OPENSTACK_CREDENTIAL @@ -94,8 +95,11 @@ topology_template: properties: unpack_credential: user: gigaspaces - token: { get_property: [ SELF, app_endpoint, protocol ] } + 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
