http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py b/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py deleted file mode 100644 index 590c6a0..0000000 --- a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/functions.py +++ /dev/null @@ -1,677 +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 StringIO import StringIO # Note: cStringIO does not support Unicode -import re - -from aria.utils.collections import FrozenList -from aria.utils.formatting import (as_raw, safe_repr) -from aria.utils.type import full_type_name -from aria.parser import implements_specification -from aria.parser.exceptions import InvalidValueError -from aria.parser.validation import Issue -from aria.modeling.exceptions import CannotEvaluateFunctionException -from aria.modeling.models import (Node, NodeTemplate, Relationship, RelationshipTemplate) -from aria.modeling.functions import (Function, Evaluation) - - -# -# Intrinsic -# - -@implements_specification('4.3.1', 'tosca-simple-1.0') -class Concat(Function): - """ - The ``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() or u'' - return Evaluation(value, final) - - -@implements_specification('4.3.2', 'tosca-simple-1.0') -class Token(Function): - """ - The ``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 -# - -@implements_specification('4.4.1', 'tosca-simple-1.0') -class GetInput(Function): - """ - The ``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): - service = container_holder.service - if service is None: - raise CannotEvaluateFunctionException() - - value = service.inputs.get(self.input_property_name) - if value is not None: - value = value.value - return Evaluation(value, False) # We never return final evaluations! - - raise InvalidValueError( - 'function "get_input" argument is not a valid input name: {0}' - .format(safe_repr(self.input_property_name)), - locator=self.locator) - - -@implements_specification('4.4.2', 'tosca-simple-1.0') -class GetProperty(Function): - """ - The ``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 -# - -@implements_specification('4.5.1', 'tosca-simple-1.0') -class GetAttribute(Function): - """ - The ``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 -# - -@implements_specification('4.6.1', 'tosca-simple-1.0') # pylint: disable=abstract-method -class GetOperationOutput(Function): - """ - The ``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 -# - -@implements_specification('4.7.1', 'tosca-simple-1.0') -class GetNodesOfType(Function): - """ - The ``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 -# - -@implements_specification('4.8.1', 'tosca-simple-1.0') # pylint: disable=abstract-method -class GetArtifact(Function): - """ - The ``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): - """ - Calls ``__evaluate__`` and passes on ``final`` state. - """ - - if hasattr(value, '__evaluate__'): - value = value.__evaluate__(container_holder) - if not value.final: - final = False - return value.value, final - else: - return value, final - - -@implements_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 - - raise InvalidValueError('function "{0}" could not find modelable entity "{1}"' - .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 ``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_or_index in nested_parameter_name_or_index: - if (isinstance(value, dict) and (name_or_index in value)) \ - or ((isinstance(value, list) and (name_or_index < len(value)))): - value = value[name_or_index] # Parameter - # We are not using Parameter.value, but rather Parameter._value, because we want to make - # sure to get "final" (it is swallowed by Parameter.value) - value, final = evaluate(value._value, final, value) - 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-website/blob/23d6ba76/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/interfaces.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/interfaces.py b/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/interfaces.py deleted file mode 100644 index e04ac4a..0000000 --- a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/interfaces.py +++ /dev/null @@ -1,522 +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 aria.utils.collections import (merge, deepcopy_with_locators, OrderedDict) -from aria.parser.presentation import get_locator -from aria.parser.validation import Issue - -from .parameters import (coerce_parameter_value, convert_parameter_definitions_to_values) - - -# -# InterfaceType -# - -def get_inherited_operations(context, presentation): - """ - Returns our operation definitions added on top of those of our parent, if we have one - (recursively). - - Allows overriding all aspects of parent operations except input data types. - """ - - # Get operations from parent - parent = presentation._get_parent(context) - operations = get_inherited_operations(context, parent) if parent is not None else OrderedDict() - - # Add/merge our operations - our_operations = presentation.operations # OperationDefinition - merge_operation_definitions(context, operations, our_operations, presentation._name, - presentation, 'type') - - for operation in operations.itervalues(): - operation._reset_method_cache() - - return operations - - -# -# InterfaceDefinition -# - -def get_and_override_input_definitions_from_type(context, presentation): - """ - Returns our input definitions added on top of those of the interface type, if specified. - - Allows overriding all aspects of parent interface type inputs except data types. - """ - - inputs = OrderedDict() - - # Get inputs from type - the_type = presentation._get_type(context) # IntefaceType - type_inputs = the_type._get_inputs(context) if the_type is not None else None - if type_inputs: - for input_name, type_input in type_inputs.iteritems(): - inputs[input_name] = type_input._clone(presentation) - - # Add/merge our inputs - our_inputs = presentation.inputs # PropertyDefinition - if our_inputs: - merge_input_definitions(context, inputs, our_inputs, presentation._name, None, presentation, - 'definition') - - return inputs - - -def get_and_override_operation_definitions_from_type(context, presentation): - """ - Returns our operation definitions added on top of those of the interface type, if specified. - - Allows overriding all aspects of parent interface type inputs except data types. - """ - - operations = OrderedDict() - - # Get operations from type - the_type = presentation._get_type(context) # InterfaceType - type_operations = the_type._get_operations(context) if the_type is not None else None - if type_operations: - for operations_name, type_operation in type_operations.iteritems(): - operations[operations_name] = type_operation._clone(presentation) - - # Add/merge our operations - our_operations = presentation.operations # OperationDefinition - merge_operation_definitions(context, operations, our_operations, presentation._name, - presentation, 'definition') - - return operations - - -# -# NodeType, RelationshipType, GroupType -# - -def get_inherited_interface_definitions(context, presentation, type_name, for_presentation=None): - """ - Returns our interface definitions added on top of those of our parent, if we have one - (recursively). - - Allows overriding all aspects of parent interfaces except interface and operation input data - types. - """ - - # Get interfaces from parent - parent = presentation._get_parent(context) - interfaces = get_inherited_interface_definitions(context, parent, type_name, presentation) \ - if parent is not None else OrderedDict() - - # Add/merge interfaces from their types - merge_interface_definitions_from_their_types(context, interfaces, presentation) - - # Add/merge our interfaces - our_interfaces = presentation.interfaces - merge_interface_definitions(context, interfaces, our_interfaces, presentation, - for_presentation=for_presentation) - - return interfaces - - -# -# NodeTemplate, RelationshipTemplate, GroupTemplate -# - -def get_template_interfaces(context, presentation, type_name): - """ - Returns the assigned interface_template values while making sure they are defined in the type. - This includes the interfaces themselves, their operations, and inputs for interfaces and - operations. - - Interface and operation inputs' default values, if available, will be used if we did not assign - them. - - Makes sure that required inputs indeed end up with a value. - - This code is especially complex due to the many levels of nesting involved. - """ - - template_interfaces = OrderedDict() - - the_type = presentation._get_type(context) # NodeType, RelationshipType, GroupType - # InterfaceDefinition (or InterfaceAssignment in the case of RelationshipTemplate): - interface_definitions = the_type._get_interfaces(context) if the_type is not None else None - - # Copy over interfaces from the type (will initialize inputs with default values) - if interface_definitions is not None: - for interface_name, interface_definition in interface_definitions.iteritems(): - # Note that in the case of a RelationshipTemplate, we will already have the values as - # InterfaceAssignment. It will not be converted, just cloned. - template_interfaces[interface_name] = \ - convert_interface_definition_from_type_to_template(context, interface_definition, - presentation) - - # Fill in our interfaces - our_interface_assignments = presentation.interfaces - if our_interface_assignments: - # InterfaceAssignment: - for interface_name, our_interface_assignment in our_interface_assignments.iteritems(): - if interface_name in template_interfaces: - interface_assignment = template_interfaces[interface_name] # InterfaceAssignment - # InterfaceDefinition (or InterfaceAssignment in the case of RelationshipTemplate): - interface_definition = interface_definitions[interface_name] - merge_interface(context, presentation, interface_assignment, - our_interface_assignment, interface_definition, interface_name) - else: - context.validation.report( - 'interface definition "%s" not declared at %s "%s" in "%s"' - % (interface_name, type_name, presentation.type, presentation._fullname), - locator=our_interface_assignment._locator, level=Issue.BETWEEN_TYPES) - - # Check that there are no required inputs that we haven't assigned - for interface_name, interface_template in template_interfaces.iteritems(): - if interface_name in interface_definitions: - # InterfaceDefinition (or InterfaceAssignment in the case of RelationshipTemplate): - interface_definition = interface_definitions[interface_name] - our_interface_assignment = our_interface_assignments.get(interface_name) \ - if our_interface_assignments is not None else None - validate_required_inputs(context, presentation, interface_template, - interface_definition, our_interface_assignment, interface_name) - - return template_interfaces - - -# -# Utils -# - -def convert_interface_definition_from_type_to_template(context, presentation, container): - from ..assignments import InterfaceAssignment - - if isinstance(presentation, InterfaceAssignment): - # Nothing to convert, so just clone - return presentation._clone(container) - - raw = convert_interface_definition_from_type_to_raw_template(context, presentation) - return InterfaceAssignment(name=presentation._name, raw=raw, container=container) - - -def convert_interface_definition_from_type_to_raw_template(context, presentation): # pylint: disable=invalid-name - raw = OrderedDict() - - # Copy default values for inputs - inputs = presentation._get_inputs(context) - if inputs is not None: - raw['inputs'] = convert_parameter_definitions_to_values(context, inputs) - - # Copy operations - operations = presentation._get_operations(context) - if operations: - for operation_name, operation in operations.iteritems(): - raw[operation_name] = OrderedDict() - description = operation.description - if description is not None: - raw[operation_name]['description'] = deepcopy_with_locators(description._raw) - implementation = operation.implementation - if implementation is not None: - raw[operation_name]['implementation'] = deepcopy_with_locators(implementation._raw) - inputs = operation.inputs - if inputs is not None: - raw[operation_name]['inputs'] = convert_parameter_definitions_to_values(context, - inputs) - - return raw - - -def convert_requirement_interface_definitions_from_type_to_raw_template(context, raw_requirement, # pylint: disable=invalid-name - interface_definitions): - if not interface_definitions: - return - if 'interfaces' not in raw_requirement: - raw_requirement['interfaces'] = OrderedDict() - for interface_name, interface_definition in interface_definitions.iteritems(): - raw_interface = convert_interface_definition_from_type_to_raw_template(context, - interface_definition) - if interface_name in raw_requirement['interfaces']: - merge(raw_requirement['interfaces'][interface_name], raw_interface) - else: - raw_requirement['interfaces'][interface_name] = raw_interface - - -def merge_interface(context, presentation, interface_assignment, our_interface_assignment, - interface_definition, interface_name): - # Assign/merge interface inputs - assign_raw_inputs(context, interface_assignment._raw, our_interface_assignment.inputs, - interface_definition._get_inputs(context), interface_name, None, presentation) - - # Assign operation implementations and inputs - our_operation_templates = our_interface_assignment.operations # OperationAssignment - # OperationDefinition or OperationAssignment: - operation_definitions = interface_definition._get_operations(context) \ - if hasattr(interface_definition, '_get_operations') else interface_definition.operations - if our_operation_templates: - # OperationAssignment: - for operation_name, our_operation_template in our_operation_templates.iteritems(): - operation_definition = operation_definitions.get(operation_name) # OperationDefinition - - our_input_assignments = our_operation_template.inputs - our_implementation = our_operation_template.implementation - - if operation_definition is None: - context.validation.report( - 'interface definition "%s" refers to an unknown operation "%s" in "%s"' - % (interface_name, operation_name, presentation._fullname), - locator=our_operation_template._locator, level=Issue.BETWEEN_TYPES) - - if (our_input_assignments is not None) or (our_implementation is not None): - # Make sure we have the dict - if (operation_name not in interface_assignment._raw) \ - or (interface_assignment._raw[operation_name] is None): - interface_assignment._raw[operation_name] = OrderedDict() - - if our_implementation is not None: - interface_assignment._raw[operation_name]['implementation'] = \ - deepcopy_with_locators(our_implementation._raw) - - # Assign/merge operation inputs - input_definitions = operation_definition.inputs \ - if operation_definition is not None else None - assign_raw_inputs(context, interface_assignment._raw[operation_name], - our_input_assignments, input_definitions, interface_name, - operation_name, presentation) - - -def merge_raw_input_definition(context, the_raw_input, our_input, interface_name, operation_name, - presentation, type_name): - # Check if we changed the type - # TODO: allow a sub-type? - input_type1 = the_raw_input.get('type') - input_type2 = our_input.type - if input_type1 != input_type2: - if operation_name is not None: - context.validation.report( - 'interface %s "%s" changes operation input "%s.%s" type from "%s" to "%s" in "%s"' - % (type_name, interface_name, operation_name, our_input._name, input_type1, - input_type2, presentation._fullname), - locator=input_type2._locator, level=Issue.BETWEEN_TYPES) - else: - context.validation.report( - 'interface %s "%s" changes input "%s" type from "%s" to "%s" in "%s"' - % (type_name, interface_name, our_input._name, input_type1, input_type2, - presentation._fullname), - locator=input_type2._locator, level=Issue.BETWEEN_TYPES) - - # Merge - merge(the_raw_input, our_input._raw) - - -def merge_input_definitions(context, inputs, our_inputs, interface_name, operation_name, - presentation, type_name): - for input_name, our_input in our_inputs.iteritems(): - if input_name in inputs: - merge_raw_input_definition(context, inputs[input_name]._raw, our_input, interface_name, - operation_name, presentation, type_name) - else: - inputs[input_name] = our_input._clone(presentation) - - -def merge_raw_input_definitions(context, raw_inputs, our_inputs, interface_name, operation_name, - presentation, type_name): - for input_name, our_input in our_inputs.iteritems(): - if input_name in raw_inputs: - merge_raw_input_definition(context, raw_inputs[input_name], our_input, interface_name, - operation_name, presentation, type_name) - else: - raw_inputs[input_name] = deepcopy_with_locators(our_input._raw) - - -def merge_raw_operation_definition(context, raw_operation, our_operation, interface_name, - presentation, type_name): - if not isinstance(our_operation._raw, dict): - # Convert short form to long form - raw_operation['implementation'] = deepcopy_with_locators(our_operation._raw) - return - - # Add/merge inputs - our_operation_inputs = our_operation.inputs - if our_operation_inputs: - # Make sure we have the dict - if ('inputs' not in raw_operation) or (raw_operation.get('inputs') is None): - raw_operation['inputs'] = OrderedDict() - - merge_raw_input_definitions(context, raw_operation['inputs'], our_operation_inputs, - interface_name, our_operation._name, presentation, type_name) - - # Override the description - if our_operation._raw.get('description') is not None: - raw_operation['description'] = deepcopy_with_locators(our_operation._raw['description']) - - # Add/merge implementation - if our_operation._raw.get('implementation') is not None: - if raw_operation.get('implementation') is not None: - merge(raw_operation['implementation'], - deepcopy_with_locators(our_operation._raw['implementation'])) - else: - raw_operation['implementation'] = \ - deepcopy_with_locators(our_operation._raw['implementation']) - - -def merge_operation_definitions(context, operations, our_operations, interface_name, presentation, - type_name): - if not our_operations: - return - for operation_name, our_operation in our_operations.iteritems(): - if operation_name in operations: - merge_raw_operation_definition(context, operations[operation_name]._raw, our_operation, - interface_name, presentation, type_name) - else: - operations[operation_name] = our_operation._clone(presentation) - - -def merge_raw_operation_definitions(context, raw_operations, our_operations, interface_name, - presentation, type_name): - for operation_name, our_operation in our_operations.iteritems(): - if operation_name in raw_operations: - raw_operation = raw_operations[operation_name] - if isinstance(raw_operation, basestring): - # Convert short form to long form - raw_operations[operation_name] = OrderedDict((('implementation', raw_operation),)) - raw_operation = raw_operations[operation_name] - merge_raw_operation_definition(context, raw_operation, our_operation, interface_name, - presentation, type_name) - else: - raw_operations[operation_name] = deepcopy_with_locators(our_operation._raw) - - -# From either an InterfaceType or an InterfaceDefinition: -def merge_interface_definition(context, interface, our_source, presentation, type_name): - if hasattr(our_source, 'type'): - # Check if we changed the interface type - input_type1 = interface.type - input_type2 = our_source.type - if (input_type1 is not None) and (input_type2 is not None) and (input_type1 != input_type2): - context.validation.report( - 'interface definition "%s" changes type from "%s" to "%s" in "%s"' - % (interface._name, input_type1, input_type2, presentation._fullname), - locator=input_type2._locator, level=Issue.BETWEEN_TYPES) - - # Add/merge inputs - our_interface_inputs = our_source._get_inputs(context) \ - if hasattr(our_source, '_get_inputs') else our_source.inputs - if our_interface_inputs: - # Make sure we have the dict - if ('inputs' not in interface._raw) or (interface._raw.get('inputs') is None): - interface._raw['inputs'] = OrderedDict() - - merge_raw_input_definitions(context, interface._raw['inputs'], our_interface_inputs, - our_source._name, None, presentation, type_name) - - # Add/merge operations - our_operations = our_source._get_operations(context) \ - if hasattr(our_source, '_get_operations') else our_source.operations - if our_operations is not None: - merge_raw_operation_definitions(context, interface._raw, our_operations, our_source._name, - presentation, type_name) - - -def merge_interface_definitions(context, interfaces, our_interfaces, presentation, - for_presentation=None): - if not our_interfaces: - return - for name, our_interface in our_interfaces.iteritems(): - if name in interfaces: - merge_interface_definition(context, interfaces[name], our_interface, presentation, - 'definition') - else: - interfaces[name] = our_interface._clone(for_presentation) - - -def merge_interface_definitions_from_their_types(context, interfaces, presentation): - for interface in interfaces.itervalues(): - the_type = interface._get_type(context) # InterfaceType - if the_type is not None: - merge_interface_definition(context, interface, the_type, presentation, 'type') - - -def assign_raw_inputs(context, values, assignments, definitions, interface_name, operation_name, - presentation): - if not assignments: - return - - # Make sure we have the dict - if ('inputs' not in values) or (values['inputs'] is None): - values['inputs'] = OrderedDict() - - # Assign inputs - for input_name, assignment in assignments.iteritems(): - if (definitions is not None) and (input_name not in definitions): - if operation_name is not None: - context.validation.report( - 'interface definition "%s" assigns a value to an unknown operation input' - ' "%s.%s" in "%s"' - % (interface_name, operation_name, input_name, presentation._fullname), - locator=assignment._locator, level=Issue.BETWEEN_TYPES) - else: - context.validation.report( - 'interface definition "%s" assigns a value to an unknown input "%s" in "%s"' - % (interface_name, input_name, presentation._fullname), - locator=assignment._locator, level=Issue.BETWEEN_TYPES) - - definition = definitions.get(input_name) if definitions is not None else None - - # Note: default value has already been assigned - - # Coerce value - values['inputs'][input_name] = coerce_parameter_value(context, assignment, definition, - assignment.value) - - -def validate_required_inputs(context, presentation, assignment, definition, original_assignment, - interface_name, operation_name=None): - input_definitions = definition.inputs - if input_definitions: - for input_name, input_definition in input_definitions.iteritems(): - if input_definition.required: - prop = assignment.inputs.get(input_name) \ - if ((assignment is not None) and (assignment.inputs is not None)) else None - value = prop.value if prop is not None else None - value = value.value if value is not None else None - if value is None: - if operation_name is not None: - context.validation.report( - 'interface definition "%s" does not assign a value to a required' - ' operation input "%s.%s" in "%s"' - % (interface_name, operation_name, input_name, presentation._fullname), - locator=get_locator(original_assignment, presentation._locator), - level=Issue.BETWEEN_TYPES) - else: - context.validation.report( - 'interface definition "%s" does not assign a value to a required input' - ' "%s" in "%s"' - % (interface_name, input_name, presentation._fullname), - locator=get_locator(original_assignment, presentation._locator), - level=Issue.BETWEEN_TYPES) - - if operation_name is not None: - return - - assignment_operations = assignment.operations - operation_definitions = definition._get_operations(context) - if operation_definitions: - for operation_name, operation_definition in operation_definitions.iteritems(): - assignment_operation = assignment_operations.get(operation_name) \ - if assignment_operations is not None else None - original_operation = \ - original_assignment.operations.get(operation_name, original_assignment) \ - if (original_assignment is not None) \ - and (original_assignment.operations is not None) \ - else original_assignment - validate_required_inputs(context, presentation, assignment_operation, - operation_definition, original_operation, interface_name, - operation_name) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/parameters.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/parameters.py b/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/parameters.py deleted file mode 100644 index c910956..0000000 --- a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/parameters.py +++ /dev/null @@ -1,211 +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 aria.utils.collections import (merge, deepcopy_with_locators, OrderedDict) -from aria.utils.formatting import pluralize -from aria.parser.presentation import Value -from aria.parser.validation import Issue - -from .data_types import coerce_value - - -# -# ArtifactType, DataType, CapabilityType, RelationshipType, NodeType, GroupType, PolicyType -# - -def get_inherited_parameter_definitions(context, presentation, field_name, for_presentation=None): - """ - Returns our parameter definitions added on top of those of our parent, if we have one - (recursively). - - Allows overriding all aspects of parent properties except data type. - """ - - # Get definitions from parent - # If we inherit from a primitive, it does not have a parent: - parent = presentation._get_parent(context) if hasattr(presentation, '_get_parent') else None - definitions = get_inherited_parameter_definitions(context, parent, field_name, - for_presentation=presentation) \ - if parent is not None else OrderedDict() - - # Add/merge our definitions - # If we inherit from a primitive, it does not have our field - our_definitions = getattr(presentation, field_name, None) - if our_definitions: - our_definitions_clone = OrderedDict() - for name, our_definition in our_definitions.iteritems(): - our_definitions_clone[name] = our_definition._clone(for_presentation) - our_definitions = our_definitions_clone - merge_parameter_definitions(context, presentation, definitions, our_definitions, field_name) - - for definition in definitions.itervalues(): - definition._reset_method_cache() - - return definitions - - -# -# NodeTemplate, RelationshipTemplate, GroupTemplate, PolicyTemplate -# - -def get_assigned_and_defined_parameter_values(context, presentation, field_name): - """ - Returns the assigned property values while making sure they are defined in our type. - - The property definition's default value, if available, will be used if we did not assign it. - - Makes sure that required properties indeed end up with a value. - """ - - values = OrderedDict() - - the_type = presentation._get_type(context) - field_name_plural = pluralize(field_name) - 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: - for name, value in assignments.iteritems(): - if (definitions is not None) and (name in definitions): - definition = definitions[name] - values[name] = coerce_parameter_value(context, value, definition, value.value) - else: - 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: - values[name] = coerce_parameter_value(context, presentation, definition, - definition.default) - - validate_required_values(context, presentation, values, definitions) - - return values - - -# -# TopologyTemplate -# - -def get_parameter_values(context, presentation, field_name): - values = OrderedDict() - - parameters = getattr(presentation, field_name) - - # Fill in defaults and values - if parameters: - for name, parameter in parameters.iteritems(): - if values.get(name) is None: - if hasattr(parameter, 'value') and (parameter.value is not None): - # For parameters only: - values[name] = coerce_parameter_value(context, presentation, parameter, - parameter.value) - else: - default = parameter.default if hasattr(parameter, 'default') else None - values[name] = coerce_parameter_value(context, presentation, parameter, default) - - return values - - -# -# Utils -# - -def validate_required_values(context, presentation, values, definitions): - """ - Check if required properties have not been assigned. - """ - - if not definitions: - return - for name, definition in definitions.iteritems(): - if getattr(definition, 'required', False) \ - and ((values is None) or (values.get(name) is None)): - context.validation.report('required property "%s" is not assigned a value in "%s"' - % (name, presentation._fullname), - locator=presentation._get_child_locator('properties'), - level=Issue.BETWEEN_TYPES) - - -def merge_raw_parameter_definition(context, presentation, raw_property_definition, - our_property_definition, field_name, property_name): - # Check if we changed the type - # TODO: allow a sub-type? - type1 = raw_property_definition.get('type') - type2 = our_property_definition.type - if type1 != type2: - context.validation.report( - 'override changes type from "%s" to "%s" for property "%s" in "%s"' - % (type1, type2, property_name, presentation._fullname), - locator=presentation._get_child_locator(field_name, property_name), - level=Issue.BETWEEN_TYPES) - - merge(raw_property_definition, our_property_definition._raw) - - -def merge_raw_parameter_definitions(context, presentation, raw_property_definitions, - our_property_definitions, field_name): - if not our_property_definitions: - return - for property_name, our_property_definition in our_property_definitions.iteritems(): - if property_name in raw_property_definitions: - raw_property_definition = raw_property_definitions[property_name] - merge_raw_parameter_definition(context, presentation, raw_property_definition, - our_property_definition, field_name, property_name) - else: - raw_property_definitions[property_name] = \ - deepcopy_with_locators(our_property_definition._raw) - - -def merge_parameter_definitions(context, presentation, property_definitions, - our_property_definitions, field_name): - if not our_property_definitions: - return - for property_name, our_property_definition in our_property_definitions.iteritems(): - if property_name in property_definitions: - property_definition = property_definitions[property_name] - merge_raw_parameter_definition(context, presentation, property_definition._raw, - our_property_definition, field_name, property_name) - else: - property_definitions[property_name] = our_property_definition - - -# Works on properties, inputs, and parameters -def coerce_parameter_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) 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 - else: - type_name = getattr(definition, 'type', None) - description = getattr(definition, 'description', None) - description = description.value if description is not None else None - return Value(type_name, value, description) - - -def convert_parameter_definitions_to_values(context, definitions): - values = OrderedDict() - for name, definition in definitions.iteritems(): - default = definition.default - values[name] = coerce_parameter_value(context, definition, definition, default) - return values http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/policies.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/policies.py b/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/policies.py deleted file mode 100644 index 7dd803b..0000000 --- a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/policies.py +++ /dev/null @@ -1,81 +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 ..presentation.types import convert_shorthand_to_full_type_name - - -# -# PolicyType -# - -def get_inherited_targets(context, presentation): - """ - Returns our target node types and group types if we have them or those of our parent, if we have - one (recursively). - """ - - parent = presentation._get_parent(context) - - node_types, group_types = get_inherited_targets(context, parent) \ - if parent is not None else ([], []) - - our_targets = presentation.targets - if our_targets: - all_node_types = context.presentation.get('service_template', 'node_types') or {} - all_group_types = context.presentation.get('service_template', 'group_types') or {} - node_types = [] - group_types = [] - - for our_target in our_targets: - if our_target in all_node_types: - our_target = convert_shorthand_to_full_type_name(context, our_target, - all_node_types) - node_types.append(all_node_types[our_target]) - elif our_target in all_group_types: - our_target = convert_shorthand_to_full_type_name(context, our_target, - all_group_types) - group_types.append(all_group_types[our_target]) - - return node_types, group_types - - -# -# PolicyTemplate -# - -def get_policy_targets(context, presentation): - """ - Returns our target node templates and groups if we have them. - """ - - node_templates = [] - groups = [] - - our_targets = presentation.targets - if our_targets: - all_node_templates = \ - context.presentation.get('service_template', 'topology_template', 'node_templates') \ - or {} - all_groups = \ - context.presentation.get('service_template', 'topology_template', 'groups') \ - or {} - - for our_target in our_targets: - if our_target in all_node_templates: - node_templates.append(all_node_templates[our_target]) - elif our_target in all_groups: - groups.append(all_groups[our_target]) - - return node_templates, groups http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/requirements.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/requirements.py b/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/requirements.py deleted file mode 100644 index 6bdb5b1..0000000 --- a/apache-ariatosca-0.1.1/extensions/aria_extension_tosca/simple_v1_0/modeling/requirements.py +++ /dev/null @@ -1,364 +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 aria.parser.validation import Issue -from aria.utils.collections import (deepcopy_with_locators, OrderedDict) - -from .parameters import (convert_parameter_definitions_to_values, validate_required_values, - coerce_parameter_value) -from .interfaces import (convert_requirement_interface_definitions_from_type_to_raw_template, - merge_interface_definitions, merge_interface, validate_required_inputs) - - -# -# NodeType -# - -def get_inherited_requirement_definitions(context, presentation): - """ - Returns our requirement definitions added on top of those of our parent, if we have one - (recursively). - - Allows overriding requirement definitions if they have the same name. - """ - - parent = presentation._get_parent(context) - requirement_definitions = get_inherited_requirement_definitions(context, parent) \ - if parent is not None else [] - - our_requirement_definitions = presentation.requirements - if our_requirement_definitions: - for requirement_name, our_requirement_definition in our_requirement_definitions: - # Remove existing requirement definitions of this name if they exist - for name, requirement_definition in requirement_definitions: - if name == requirement_name: - requirement_definitions.remove((name, requirement_definition)) - - requirement_definitions.append((requirement_name, our_requirement_definition)) - - return requirement_definitions - - -# -# NodeTemplate -# - -def get_template_requirements(context, presentation): - """ - Returns our requirements added on top of those of the node type if they exist there. - - If the requirement has a relationship, the relationship properties and interfaces are assigned. - - Returns the assigned property, interface input, and interface operation input values while - making sure they are defined in our type. Default values, if available, will be used if we did - not assign them. Also makes sure that required properties and inputs indeed end up with a value. - """ - - requirement_assignments = [] - - the_type = presentation._get_type(context) # NodeType - requirement_definitions = the_type._get_requirements(context) if the_type is not None else None - - # Add our requirement assignments - our_requirement_assignments = presentation.requirements - if our_requirement_assignments: - add_requirement_assignments(context, presentation, requirement_assignments, - requirement_definitions, our_requirement_assignments) - - # Validate occurrences - if requirement_definitions: - for requirement_name, requirement_definition in requirement_definitions: - # Allowed occurrences - allowed_occurrences = requirement_definition.occurrences - allowed_occurrences = allowed_occurrences if allowed_occurrences is not None else None - - # Count actual occurrences - actual_occurrences = 0 - for name, _ in requirement_assignments: - if name == requirement_name: - actual_occurrences += 1 - - if allowed_occurrences is None: - # If not specified, we interpret this to mean that exactly 1 occurrence is required - if actual_occurrences == 0: - # If it's not there, we will automatically add it (this behavior is not in the - # TOSCA spec, but seems implied) - requirement_assignment, \ - relationship_property_definitions, \ - relationship_interface_definitions = \ - convert_requirement_from_definition_to_assignment(context, - requirement_definition, - None, presentation) - validate_requirement_assignment(context, presentation, requirement_assignment, - relationship_property_definitions, - relationship_interface_definitions) - requirement_assignments.append((requirement_name, requirement_assignment)) - elif actual_occurrences > 1: - context.validation.report( - 'requirement "%s" is allowed only one occurrence in "%s": %d' - % (requirement_name, presentation._fullname, actual_occurrences), - locator=presentation._locator, level=Issue.BETWEEN_TYPES) - else: - if not allowed_occurrences.is_in(actual_occurrences): - if allowed_occurrences.value[1] == 'UNBOUNDED': - context.validation.report( - 'requirement "%s" does not have at least %d occurrences in "%s": has %d' - % (requirement_name, allowed_occurrences.value[0], - presentation._fullname, actual_occurrences), - locator=presentation._locator, level=Issue.BETWEEN_TYPES) - else: - context.validation.report( - 'requirement "%s" is allowed between %d and %d occurrences in "%s":' - ' has %d' - % (requirement_name, allowed_occurrences.value[0], - allowed_occurrences.value[1], presentation._fullname, - actual_occurrences), - locator=presentation._locator, level=Issue.BETWEEN_TYPES) - - return requirement_assignments - - -# -# Utils -# - -def convert_requirement_from_definition_to_assignment(context, requirement_definition, # pylint: disable=too-many-branches - our_requirement_assignment, container): - from ..assignments import RequirementAssignment - - raw = OrderedDict() - - # Capability type name: - raw['capability'] = deepcopy_with_locators(requirement_definition.capability) - - node_type = requirement_definition._get_node_type(context) - if node_type is not None: - raw['node'] = deepcopy_with_locators(node_type._name) - - relationship_type = None - relationship_template = None - relationship_property_definitions = None - relationship_interface_definitions = None - - # First try to find the relationship if we declared it - # RelationshipAssignment: - our_relationship = our_requirement_assignment.relationship \ - if our_requirement_assignment is not None else None - if our_relationship is not None: - relationship_type, relationship_type_variant = our_relationship._get_type(context) - if relationship_type_variant == 'relationship_template': - relationship_template = relationship_type - relationship_type = relationship_template._get_type(context) - - definition_relationship_type = None - relationship_definition = requirement_definition.relationship # RelationshipDefinition - if relationship_definition is not None: - definition_relationship_type = relationship_definition._get_type(context) - - # If not exists, try at the node type - if relationship_type is None: - relationship_type = definition_relationship_type - else: - # Make sure the type is derived - if not definition_relationship_type._is_descendant(context, relationship_type): - context.validation.report( - 'assigned relationship type "%s" is not a descendant of declared relationship type' - ' "%s"' \ - % (relationship_type._name, definition_relationship_type._name), - locator=container._locator, level=Issue.BETWEEN_TYPES) - - if relationship_type is not None: - raw['relationship'] = OrderedDict() - - type_name = our_relationship.type if our_relationship is not None else None - if type_name is None: - type_name = relationship_type._name - - raw['relationship']['type'] = deepcopy_with_locators(type_name) - - # These are our property definitions - relationship_property_definitions = relationship_type._get_properties(context) - - if relationship_template is not None: - # Property values from template - raw['relationship']['properties'] = relationship_template._get_property_values(context) - else: - if relationship_property_definitions: - # Convert property definitions to values - raw['relationship']['properties'] = \ - convert_parameter_definitions_to_values(context, - relationship_property_definitions) - - # These are our interface definitions - # InterfaceDefinition: - relationship_interface_definitions = OrderedDict(relationship_type._get_interfaces(context)) - - # Convert interface definitions to templates - convert_requirement_interface_definitions_from_type_to_raw_template( - context, - raw['relationship'], - relationship_interface_definitions) - - if relationship_definition: - # Merge extra interface definitions - # InterfaceDefinition: - definition_interface_definitions = relationship_definition.interfaces - merge_interface_definitions(context, relationship_interface_definitions, - definition_interface_definitions, requirement_definition, - container) - - if relationship_template is not None: - # Interfaces from template - interfaces = relationship_template._get_interfaces(context) - if interfaces: - raw['relationship']['interfaces'] = OrderedDict() - for interface_name, interface in interfaces.iteritems(): - raw['relationship']['interfaces'][interface_name] = interface._raw - - return \ - RequirementAssignment(name=requirement_definition._name, raw=raw, container=container), \ - relationship_property_definitions, \ - relationship_interface_definitions - - -def add_requirement_assignments(context, presentation, requirement_assignments, - requirement_definitions, our_requirement_assignments): - for requirement_name, our_requirement_assignment in our_requirement_assignments: - requirement_definition = get_first_requirement(requirement_definitions, requirement_name) - if requirement_definition is not None: - requirement_assignment, \ - relationship_property_definitions, \ - relationship_interface_definitions = \ - convert_requirement_from_definition_to_assignment(context, requirement_definition, - our_requirement_assignment, - presentation) - merge_requirement_assignment(context, - relationship_property_definitions, - relationship_interface_definitions, - requirement_assignment, our_requirement_assignment) - validate_requirement_assignment(context, - our_requirement_assignment.relationship \ - or our_requirement_assignment, - requirement_assignment, - relationship_property_definitions, - relationship_interface_definitions) - requirement_assignments.append((requirement_name, requirement_assignment)) - else: - context.validation.report('requirement "%s" not declared at node type "%s" in "%s"' - % (requirement_name, presentation.type, - presentation._fullname), - locator=our_requirement_assignment._locator, - level=Issue.BETWEEN_TYPES) - - -def merge_requirement_assignment(context, relationship_property_definitions, - relationship_interface_definitions, requirement, our_requirement): - our_capability = our_requirement.capability - if our_capability is not None: - requirement._raw['capability'] = deepcopy_with_locators(our_capability) - - our_node = our_requirement.node - if our_node is not None: - requirement._raw['node'] = deepcopy_with_locators(our_node) - - our_node_filter = our_requirement.node_filter - if our_node_filter is not None: - requirement._raw['node_filter'] = deepcopy_with_locators(our_node_filter._raw) - - our_relationship = our_requirement.relationship # RelationshipAssignment - if (our_relationship is not None) and (our_relationship.type is None): - # Make sure we have a dict - if 'relationship' not in requirement._raw: - requirement._raw['relationship'] = OrderedDict() - - merge_requirement_assignment_relationship(context, our_relationship, - relationship_property_definitions, - relationship_interface_definitions, - requirement, our_relationship) - - -def merge_requirement_assignment_relationship(context, presentation, property_definitions, - interface_definitions, requirement, our_relationship): - our_relationship_properties = our_relationship._raw.get('properties') - if our_relationship_properties: - # Make sure we have a dict - if 'properties' not in requirement._raw['relationship']: - requirement._raw['relationship']['properties'] = OrderedDict() - - # Merge our properties - for property_name, prop in our_relationship_properties.iteritems(): - if property_name in property_definitions: - definition = property_definitions[property_name] - requirement._raw['relationship']['properties'][property_name] = \ - coerce_parameter_value(context, presentation, definition, prop) - else: - context.validation.report( - 'relationship property "%s" not declared at definition of requirement "%s"' - ' in "%s"' - % (property_name, requirement._fullname, - presentation._container._container._fullname), - locator=our_relationship._get_child_locator('properties', property_name), - level=Issue.BETWEEN_TYPES) - - our_interfaces = our_relationship.interfaces - if our_interfaces: - # Make sure we have a dict - if 'interfaces' not in requirement._raw['relationship']: - requirement._raw['relationship']['interfaces'] = OrderedDict() - - # Merge interfaces - for interface_name, our_interface in our_interfaces.iteritems(): - if interface_name not in requirement._raw['relationship']['interfaces']: - requirement._raw['relationship']['interfaces'][interface_name] = OrderedDict() - - if (interface_definitions is not None) and (interface_name in interface_definitions): - interface_definition = interface_definitions[interface_name] - interface_assignment = requirement.relationship.interfaces[interface_name] - merge_interface(context, presentation, interface_assignment, our_interface, - interface_definition, interface_name) - else: - context.validation.report( - 'relationship interface "%s" not declared at definition of requirement "%s"' - ' in "%s"' - % (interface_name, requirement._fullname, - presentation._container._container._fullname), - locator=our_relationship._locator, level=Issue.BETWEEN_TYPES) - - -def validate_requirement_assignment(context, presentation, requirement_assignment, - relationship_property_definitions, - relationship_interface_definitions): - relationship = requirement_assignment.relationship - if relationship is None: - return - - validate_required_values(context, presentation, relationship.properties, - relationship_property_definitions) - - if relationship_interface_definitions: - for interface_name, relationship_interface_definition \ - in relationship_interface_definitions.iteritems(): - interface_assignment = relationship.interfaces.get(interface_name) \ - if relationship.interfaces is not None else None - validate_required_inputs(context, presentation, interface_assignment, - relationship_interface_definition, None, interface_name) - - -def get_first_requirement(requirement_definitions, name): - if requirement_definitions is not None: - for requirement_name, requirement_definition in requirement_definitions: - if requirement_name == name: - return requirement_definition - return None
