http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/modeling/models.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/modeling/models.py b/apache-ariatosca-0.1.1/aria/modeling/models.py deleted file mode 100644 index cf84fdb..0000000 --- a/apache-ariatosca-0.1.1/aria/modeling/models.py +++ /dev/null @@ -1,427 +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. - -""" -Data models. - -Service template models ------------------------ - -.. autosummary:: - :nosignatures: - - aria.modeling.models.ServiceTemplate - aria.modeling.models.NodeTemplate - aria.modeling.models.GroupTemplate - aria.modeling.models.PolicyTemplate - aria.modeling.models.SubstitutionTemplate - aria.modeling.models.SubstitutionTemplateMapping - aria.modeling.models.RequirementTemplate - aria.modeling.models.RelationshipTemplate - aria.modeling.models.CapabilityTemplate - aria.modeling.models.InterfaceTemplate - aria.modeling.models.OperationTemplate - aria.modeling.models.ArtifactTemplate - aria.modeling.models.PluginSpecification - -Service instance models ------------------------ - -.. autosummary:: - :nosignatures: - - aria.modeling.models.Service - aria.modeling.models.Node - aria.modeling.models.Group - aria.modeling.models.Policy - aria.modeling.models.Substitution - aria.modeling.models.SubstitutionMapping - aria.modeling.models.Relationship - aria.modeling.models.Capability - aria.modeling.models.Interface - aria.modeling.models.Operation - aria.modeling.models.Artifact - -Common models -------------- - -.. autosummary:: - :nosignatures: - - aria.modeling.models.Output - aria.modeling.models.Input - aria.modeling.models.Configuration - aria.modeling.models.Property - aria.modeling.models.Attribute - aria.modeling.models.Type - aria.modeling.models.Metadata - -Orchestration models --------------------- - -.. autosummary:: - :nosignatures: - - aria.modeling.models.Execution - aria.modeling.models.Task - aria.modeling.models.Log - aria.modeling.models.Plugin - aria.modeling.models.Argument -""" - -# pylint: disable=abstract-method - -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy import ( - Column, - Text -) - -from . import ( - service_template, - service_instance, - service_changes, - service_common, - orchestration, - mixins, - utils -) - - -aria_declarative_base = declarative_base(cls=mixins.ModelIDMixin) - - -# See also models_to_register at the bottom of this file -__all__ = ( - 'models_to_register', - - # Service template models - 'ServiceTemplate', - 'NodeTemplate', - 'GroupTemplate', - 'PolicyTemplate', - 'SubstitutionTemplate', - 'SubstitutionTemplateMapping', - 'RequirementTemplate', - 'RelationshipTemplate', - 'CapabilityTemplate', - 'InterfaceTemplate', - 'OperationTemplate', - 'ArtifactTemplate', - 'PluginSpecification', - - # Service instance models - 'Service', - 'Node', - 'Group', - 'Policy', - 'Substitution', - 'SubstitutionMapping', - 'Relationship', - 'Capability', - 'Interface', - 'Operation', - 'Artifact', - - # Service changes models - 'ServiceUpdate', - 'ServiceUpdateStep', - 'ServiceModification', - - # Common service models - 'Input', - 'Configuration', - 'Output', - 'Property', - 'Attribute', - 'Type', - 'Metadata', - - # Orchestration models - 'Execution', - 'Plugin', - 'Task', - 'Log', - 'Argument' -) - - -# region service template models - [email protected]_doc -class ServiceTemplate(aria_declarative_base, service_template.ServiceTemplateBase): - name = Column(Text, index=True, unique=True) - - [email protected]_doc -class NodeTemplate(aria_declarative_base, service_template.NodeTemplateBase): - pass - - [email protected]_doc -class GroupTemplate(aria_declarative_base, service_template.GroupTemplateBase): - pass - - [email protected]_doc -class PolicyTemplate(aria_declarative_base, service_template.PolicyTemplateBase): - pass - - [email protected]_doc -class SubstitutionTemplate(aria_declarative_base, service_template.SubstitutionTemplateBase): - pass - - [email protected]_doc -class SubstitutionTemplateMapping(aria_declarative_base, - service_template.SubstitutionTemplateMappingBase): - pass - - [email protected]_doc -class RequirementTemplate(aria_declarative_base, service_template.RequirementTemplateBase): - pass - - [email protected]_doc -class RelationshipTemplate(aria_declarative_base, service_template.RelationshipTemplateBase): - pass - - [email protected]_doc -class CapabilityTemplate(aria_declarative_base, service_template.CapabilityTemplateBase): - pass - - [email protected]_doc -class InterfaceTemplate(aria_declarative_base, service_template.InterfaceTemplateBase): - pass - - [email protected]_doc -class OperationTemplate(aria_declarative_base, service_template.OperationTemplateBase): - pass - - [email protected]_doc -class ArtifactTemplate(aria_declarative_base, service_template.ArtifactTemplateBase): - pass - - [email protected]_doc -class PluginSpecification(aria_declarative_base, service_template.PluginSpecificationBase): - pass - -# endregion - - -# region service instance models - [email protected]_doc -class Service(aria_declarative_base, service_instance.ServiceBase): - name = Column(Text, index=True, unique=True) - - [email protected]_doc -class Node(aria_declarative_base, service_instance.NodeBase): - pass - - [email protected]_doc -class Group(aria_declarative_base, service_instance.GroupBase): - pass - - [email protected]_doc -class Policy(aria_declarative_base, service_instance.PolicyBase): - pass - - [email protected]_doc -class Substitution(aria_declarative_base, service_instance.SubstitutionBase): - pass - - [email protected]_doc -class SubstitutionMapping(aria_declarative_base, service_instance.SubstitutionMappingBase): - pass - - [email protected]_doc -class Relationship(aria_declarative_base, service_instance.RelationshipBase): - pass - - [email protected]_doc -class Capability(aria_declarative_base, service_instance.CapabilityBase): - pass - - [email protected]_doc -class Interface(aria_declarative_base, service_instance.InterfaceBase): - pass - - [email protected]_doc -class Operation(aria_declarative_base, service_instance.OperationBase): - pass - - [email protected]_doc -class Artifact(aria_declarative_base, service_instance.ArtifactBase): - pass - -# endregion - - -# region service changes models - [email protected]_doc -class ServiceUpdate(aria_declarative_base, service_changes.ServiceUpdateBase): - pass - - [email protected]_doc -class ServiceUpdateStep(aria_declarative_base, service_changes.ServiceUpdateStepBase): - pass - - [email protected]_doc -class ServiceModification(aria_declarative_base, service_changes.ServiceModificationBase): - pass - -# endregion - - -# region common service models - [email protected]_doc -class Input(aria_declarative_base, service_common.InputBase): - pass - - [email protected]_doc -class Configuration(aria_declarative_base, service_common.ConfigurationBase): - pass - - [email protected]_doc -class Output(aria_declarative_base, service_common.OutputBase): - pass - - [email protected]_doc -class Property(aria_declarative_base, service_common.PropertyBase): - pass - - [email protected]_doc -class Attribute(aria_declarative_base, service_common.AttributeBase): - pass - - [email protected]_doc -class Type(aria_declarative_base, service_common.TypeBase): - pass - - [email protected]_doc -class Metadata(aria_declarative_base, service_common.MetadataBase): - pass - -# endregion - - -# region orchestration models - [email protected]_doc -class Execution(aria_declarative_base, orchestration.ExecutionBase): - pass - - [email protected]_doc -class Plugin(aria_declarative_base, orchestration.PluginBase): - pass - - [email protected]_doc -class Task(aria_declarative_base, orchestration.TaskBase): - pass - - [email protected]_doc -class Log(aria_declarative_base, orchestration.LogBase): - pass - - [email protected]_doc -class Argument(aria_declarative_base, orchestration.ArgumentBase): - pass - -# endregion - - -# See also __all__ at the top of this file -models_to_register = ( - # Service template models - ServiceTemplate, - NodeTemplate, - GroupTemplate, - PolicyTemplate, - SubstitutionTemplate, - SubstitutionTemplateMapping, - RequirementTemplate, - RelationshipTemplate, - CapabilityTemplate, - InterfaceTemplate, - OperationTemplate, - ArtifactTemplate, - PluginSpecification, - - # Service instance models - Service, - Node, - Group, - Policy, - SubstitutionMapping, - Substitution, - Relationship, - Capability, - Interface, - Operation, - Artifact, - - # Service changes models - ServiceUpdate, - ServiceUpdateStep, - ServiceModification, - - # Common service models - Input, - Configuration, - Output, - Property, - Attribute, - Type, - Metadata, - - # Orchestration models - Execution, - Plugin, - Task, - Log, - Argument -)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/modeling/orchestration.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/modeling/orchestration.py b/apache-ariatosca-0.1.1/aria/modeling/orchestration.py deleted file mode 100644 index 7068557..0000000 --- a/apache-ariatosca-0.1.1/aria/modeling/orchestration.py +++ /dev/null @@ -1,711 +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. - -""" -ARIA modeling orchestration module -""" - -# pylint: disable=no-self-argument, no-member, abstract-method -from datetime import datetime - -from sqlalchemy import ( - Column, - Integer, - Text, - DateTime, - Boolean, - Enum, - String, - Float, - orm, - PickleType) -from sqlalchemy.ext.declarative import declared_attr - -from ..orchestrator.exceptions import (TaskAbortException, TaskRetryException) -from . import mixins -from . import ( - relationship, - types as modeling_types -) - - -class ExecutionBase(mixins.ModelMixin): - """ - Workflow execution. - """ - - __tablename__ = 'execution' - - __private_fields__ = ('service_fk', - 'service_template') - - SUCCEEDED = 'succeeded' - FAILED = 'failed' - CANCELLED = 'cancelled' - PENDING = 'pending' - STARTED = 'started' - CANCELLING = 'cancelling' - - STATES = (SUCCEEDED, FAILED, CANCELLED, PENDING, STARTED, CANCELLING) - END_STATES = (SUCCEEDED, FAILED, CANCELLED) - - VALID_TRANSITIONS = { - PENDING: (STARTED, CANCELLED), - STARTED: END_STATES + (CANCELLING,), - CANCELLING: END_STATES, - CANCELLED: PENDING - } - - # region one_to_many relationships - - @declared_attr - def inputs(cls): - """ - Execution parameters. - - :type: {:obj:`basestring`: :class:`Input`} - """ - return relationship.one_to_many(cls, 'input', dict_key='name') - - @declared_attr - def tasks(cls): - """ - Tasks. - - :type: [:class:`Task`] - """ - return relationship.one_to_many(cls, 'task') - - @declared_attr - def logs(cls): - """ - Log messages for the execution (including log messages for its tasks). - - :type: [:class:`Log`] - """ - return relationship.one_to_many(cls, 'log') - - # endregion - - # region many_to_one relationships - - @declared_attr - def service(cls): - """ - Associated service. - - :type: :class:`Service` - """ - return relationship.many_to_one(cls, 'service') - - # endregion - - # region association proxies - - @declared_attr - def service_name(cls): - return relationship.association_proxy('service', cls.name_column_name()) - - @declared_attr - def service_template(cls): - return relationship.association_proxy('service', 'service_template') - - @declared_attr - def service_template_name(cls): - return relationship.association_proxy('service', 'service_template_name') - - # endregion - - # region foreign keys - - @declared_attr - def service_fk(cls): - return relationship.foreign_key('service') - - # endregion - - created_at = Column(DateTime, index=True, doc=""" - Creation timestamp. - - :type: :class:`~datetime.datetime` - """) - - started_at = Column(DateTime, nullable=True, index=True, doc=""" - Started timestamp. - - :type: :class:`~datetime.datetime` - """) - - ended_at = Column(DateTime, nullable=True, index=True, doc=""" - Ended timestamp. - - :type: :class:`~datetime.datetime` - """) - - error = Column(Text, nullable=True, doc=""" - Error message. - - :type: :obj:`basestring` - """) - - status = Column(Enum(*STATES, name='execution_status'), default=PENDING, doc=""" - Status. - - :type: :obj:`basestring` - """) - - workflow_name = Column(Text, doc=""" - Workflow name. - - :type: :obj:`basestring` - """) - - @orm.validates('status') - def validate_status(self, key, value): - """Validation function that verifies execution status transitions are OK""" - try: - current_status = getattr(self, key) - except AttributeError: - return - valid_transitions = self.VALID_TRANSITIONS.get(current_status, []) - if all([current_status is not None, - current_status != value, - value not in valid_transitions]): - raise ValueError('Cannot change execution status from {current} to {new}'.format( - current=current_status, - new=value)) - return value - - def has_ended(self): - return self.status in self.END_STATES - - def is_active(self): - return not self.has_ended() and self.status != self.PENDING - - def __str__(self): - return '<{0} id=`{1}` (status={2})>'.format( - self.__class__.__name__, - getattr(self, self.name_column_name()), - self.status - ) - - -class TaskBase(mixins.ModelMixin): - """ - Represents the smallest unit of stateful execution in ARIA. The task state includes inputs, - outputs, as well as an atomic status, ensuring that the task can only be running once at any - given time. - - The Python :attr:`function` is usually provided by an associated :class:`Plugin`. The - :attr:`arguments` of the function should be set according to the specific signature of the - function. - - Tasks may be "one shot" or may be configured to run repeatedly in the case of failure. - - Tasks are often based on :class:`Operation`, and thus act on either a :class:`Node` or a - :class:`Relationship`, however this is not required. - """ - - __tablename__ = 'task' - - __private_fields__ = ('dependency_operation_task_fk', 'dependency_stub_task_fk', 'node_fk', - 'relationship_fk', 'plugin_fk', 'execution_fk') - - START_WORKFLOW = 'start_workflow' - END_WORKFLOW = 'end_workflow' - START_SUBWROFKLOW = 'start_subworkflow' - END_SUBWORKFLOW = 'end_subworkflow' - STUB = 'stub' - CONDITIONAL = 'conditional' - - STUB_TYPES = ( - START_WORKFLOW, - START_SUBWROFKLOW, - END_WORKFLOW, - END_SUBWORKFLOW, - STUB, - CONDITIONAL, - ) - - PENDING = 'pending' - RETRYING = 'retrying' - SENT = 'sent' - STARTED = 'started' - SUCCESS = 'success' - FAILED = 'failed' - STATES = ( - PENDING, - RETRYING, - SENT, - STARTED, - SUCCESS, - FAILED, - ) - INFINITE_RETRIES = -1 - - # region one_to_many relationships - - @declared_attr - def logs(cls): - """ - Log messages. - - :type: [:class:`Log`] - """ - return relationship.one_to_many(cls, 'log') - - @declared_attr - def arguments(cls): - """ - Arguments sent to the Python :attr:`function``. - - :type: {:obj:`basestring`: :class:`Argument`} - """ - return relationship.one_to_many(cls, 'argument', dict_key='name') - - # endregion - - # region many_one relationships - - @declared_attr - def execution(cls): - """ - Containing execution. - - :type: :class:`Execution` - """ - return relationship.many_to_one(cls, 'execution') - - @declared_attr - def node(cls): - """ - Node actor (can be ``None``). - - :type: :class:`Node` - """ - return relationship.many_to_one(cls, 'node') - - @declared_attr - def relationship(cls): - """ - Relationship actor (can be ``None``). - - :type: :class:`Relationship` - """ - return relationship.many_to_one(cls, 'relationship') - - @declared_attr - def plugin(cls): - """ - Associated plugin. - - :type: :class:`Plugin` - """ - return relationship.many_to_one(cls, 'plugin') - - # endregion - - # region association proxies - - @declared_attr - def node_name(cls): - return relationship.association_proxy('node', cls.name_column_name()) - - @declared_attr - def relationship_name(cls): - return relationship.association_proxy('relationship', cls.name_column_name()) - - @declared_attr - def execution_name(cls): - return relationship.association_proxy('execution', cls.name_column_name()) - - # endregion - - # region foreign keys - - @declared_attr - def execution_fk(cls): - return relationship.foreign_key('execution', nullable=True) - - @declared_attr - def node_fk(cls): - return relationship.foreign_key('node', nullable=True) - - @declared_attr - def relationship_fk(cls): - return relationship.foreign_key('relationship', nullable=True) - - @declared_attr - def plugin_fk(cls): - return relationship.foreign_key('plugin', nullable=True) - - # endregion - - status = Column(Enum(*STATES, name='status'), default=PENDING, doc=""" - Current atomic status ('pending', 'retrying', 'sent', 'started', 'success', 'failed'). - - :type: :obj:`basestring` - """) - - due_at = Column(DateTime, nullable=False, index=True, default=datetime.utcnow(), doc=""" - Timestamp to start the task. - - :type: :class:`~datetime.datetime` - """) - - started_at = Column(DateTime, default=None, doc=""" - Started timestamp. - - :type: :class:`~datetime.datetime` - """) - - ended_at = Column(DateTime, default=None, doc=""" - Ended timestamp. - - :type: :class:`~datetime.datetime` - """) - - attempts_count = Column(Integer, default=1, doc=""" - How many attempts occurred. - - :type: :class:`~datetime.datetime` - """) - - function = Column(String, doc=""" - Full path to Python function. - - :type: :obj:`basestring` - """) - - max_attempts = Column(Integer, default=1, doc=""" - Maximum number of attempts allowed in case of task failure. - - :type: :obj:`int` - """) - - retry_interval = Column(Float, default=0, doc=""" - Interval between task retry attemps (in seconds). - - :type: :obj:`float` - """) - - ignore_failure = Column(Boolean, default=False, doc=""" - Set to ``True`` to ignore failures. - - :type: :obj:`bool` - """) - - interface_name = Column(String, doc=""" - Name of interface on node or relationship. - - :type: :obj:`basestring` - """) - - operation_name = Column(String, doc=""" - Name of operation in interface on node or relationship. - - :type: :obj:`basestring` - """) - - _api_id = Column(String) - _executor = Column(PickleType) - _context_cls = Column(PickleType) - _stub_type = Column(Enum(*STUB_TYPES)) - - @property - def actor(self): - """ - Actor of the task (node or relationship). - """ - return self.node or self.relationship - - @orm.validates('max_attempts') - def validate_max_attempts(self, _, value): # pylint: disable=no-self-use - """ - Validates that max attempts is either -1 or a positive number. - """ - if value < 1 and value != TaskBase.INFINITE_RETRIES: - raise ValueError('Max attempts can be either -1 (infinite) or any positive number. ' - 'Got {value}'.format(value=value)) - return value - - @staticmethod - def abort(message=None): - raise TaskAbortException(message) - - @staticmethod - def retry(message=None, retry_interval=None): - raise TaskRetryException(message, retry_interval=retry_interval) - - @declared_attr - def dependencies(cls): - return relationship.many_to_many(cls, self=True) - - def has_ended(self): - return self.status in (self.SUCCESS, self.FAILED) - - def is_waiting(self): - if self._stub_type: - return not self.has_ended() - else: - return self.status in (self.PENDING, self.RETRYING) - - @classmethod - def from_api_task(cls, api_task, executor, **kwargs): - instantiation_kwargs = {} - - if hasattr(api_task.actor, 'outbound_relationships'): - instantiation_kwargs['node'] = api_task.actor - elif hasattr(api_task.actor, 'source_node'): - instantiation_kwargs['relationship'] = api_task.actor - else: - raise RuntimeError('No operation context could be created for {actor.model_cls}' - .format(actor=api_task.actor)) - - instantiation_kwargs.update( - { - 'name': api_task.name, - 'status': cls.PENDING, - 'max_attempts': api_task.max_attempts, - 'retry_interval': api_task.retry_interval, - 'ignore_failure': api_task.ignore_failure, - 'execution': api_task._workflow_context.execution, - 'interface_name': api_task.interface_name, - 'operation_name': api_task.operation_name, - - # Only non-stub tasks have these fields - 'plugin': api_task.plugin, - 'function': api_task.function, - 'arguments': api_task.arguments, - '_context_cls': api_task._context_cls, - '_executor': executor, - } - ) - - instantiation_kwargs.update(**kwargs) - - return cls(**instantiation_kwargs) - - -class LogBase(mixins.ModelMixin): - """ - Single log message. - """ - - __tablename__ = 'log' - - __private_fields__ = ('execution_fk', - 'task_fk') - - # region many_to_one relationships - - @declared_attr - def execution(cls): - """ - Containing execution. - - :type: :class:`Execution` - """ - return relationship.many_to_one(cls, 'execution') - - @declared_attr - def task(cls): - """ - Containing task (can be ``None``). - - :type: :class:`Task` - """ - return relationship.many_to_one(cls, 'task') - - # endregion - - # region foreign keys - - @declared_attr - def execution_fk(cls): - return relationship.foreign_key('execution') - - @declared_attr - def task_fk(cls): - return relationship.foreign_key('task', nullable=True) - - # endregion - - level = Column(String, doc=""" - Log level. - - :type: :obj:`basestring` - """) - - msg = Column(String, doc=""" - Log message. - - :type: :obj:`basestring` - """) - - created_at = Column(DateTime, index=True, doc=""" - Creation timestamp. - - :type: :class:`~datetime.datetime` - """) - - traceback = Column(Text, doc=""" - Error traceback in case of failure. - - :type: :class:`~datetime.datetime` - """) - - def __str__(self): - return self.msg - - def __repr__(self): - name = (self.task.actor if self.task else self.execution).name - return '{name}: {self.msg}'.format(name=name, self=self) - - -class PluginBase(mixins.ModelMixin): - """ - Installed plugin. - - Plugins are usually packaged as `wagons <https://github.com/cloudify-cosmo/wagon>`__, which - are archives of one or more `wheels <https://packaging.python.org/distributing/#wheels>`__. - Most of these fields are indeed extracted from the installed wagon's metadata. - """ - - __tablename__ = 'plugin' - - # region one_to_many relationships - - @declared_attr - def tasks(cls): - """ - Associated Tasks. - - :type: [:class:`Task`] - """ - return relationship.one_to_many(cls, 'task') - - # endregion - - archive_name = Column(Text, nullable=False, index=True, doc=""" - Filename (not the full path) of the wagon's archive, often with a ``.wgn`` extension. - - :type: :obj:`basestring` - """) - - distribution = Column(Text, doc=""" - Name of the operating system on which the wagon was installed (e.g. ``ubuntu``). - - :type: :obj:`basestring` - """) - - distribution_release = Column(Text, doc=""" - Release of the operating system on which the wagon was installed (e.g. ``trusty``). - - :type: :obj:`basestring` - """) - - distribution_version = Column(Text, doc=""" - Version of the operating system on which the wagon was installed (e.g. ``14.04``). - - :type: :obj:`basestring` - """) - - package_name = Column(Text, nullable=False, index=True, doc=""" - Primary Python package name used when the wagon was installed, which is one of the wheels in the - wagon (e.g. ``cloudify-script-plugin``). - - :type: :obj:`basestring` - """) - - package_source = Column(Text, doc=""" - Full install string for the primary Python package name used when the wagon was installed (e.g. - ``cloudify-script-plugin==1.2``). - - :type: :obj:`basestring` - """) - - package_version = Column(Text, doc=""" - Version for the primary Python package name used when the wagon was installed (e.g. ``1.2``). - - :type: :obj:`basestring` - """) - - supported_platform = Column(Text, doc=""" - If the wheels are *all* pure Python then this would be "any", otherwise it would be the - installed platform name (e.g. ``linux_x86_64``). - - :type: :obj:`basestring` - """) - - supported_py_versions = Column(modeling_types.StrictList(basestring), doc=""" - Python versions supported by all the wheels (e.g. ``["py26", "py27"]``) - - :type: [:obj:`basestring`] - """) - - wheels = Column(modeling_types.StrictList(basestring), nullable=False, doc=""" - Filenames of the wheels archived in the wagon, often with a ``.whl`` extension. - - :type: [:obj:`basestring`] - """) - - uploaded_at = Column(DateTime, nullable=False, index=True, doc=""" - Timestamp for when the wagon was installed. - - :type: :class:`~datetime.datetime` - """) - - -class ArgumentBase(mixins.ParameterMixin): - """ - Python function argument parameter. - """ - - __tablename__ = 'argument' - - # region many_to_one relationships - - @declared_attr - def task(cls): - """ - Containing task (can be ``None``); - - :type: :class:`Task` - """ - return relationship.many_to_one(cls, 'task') - - @declared_attr - def operation(cls): - """ - Containing operation (can be ``None``); - - :type: :class:`Operation` - """ - return relationship.many_to_one(cls, 'operation') - - # endregion - - # region foreign keys - - @declared_attr - def task_fk(cls): - return relationship.foreign_key('task', nullable=True) - - @declared_attr - def operation_fk(cls): - return relationship.foreign_key('operation', nullable=True) - - # endregion http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/modeling/relationship.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/modeling/relationship.py b/apache-ariatosca-0.1.1/aria/modeling/relationship.py deleted file mode 100644 index 8b6028f..0000000 --- a/apache-ariatosca-0.1.1/aria/modeling/relationship.py +++ /dev/null @@ -1,395 +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. - -""" -ARIA modeling relationship module -""" - -# pylint: disable=invalid-name, redefined-outer-name - -from sqlalchemy.orm import relationship, backref -from sqlalchemy.orm.collections import attribute_mapped_collection -from sqlalchemy.ext.associationproxy import association_proxy as original_association_proxy -from sqlalchemy import ( - Column, - ForeignKey, - Integer, - Table -) - -from ..utils import formatting - -NO_BACK_POP = 'NO_BACK_POP' - - -def foreign_key(other_table, nullable=False): - """ - Declare a foreign key property, which will also create a foreign key column in the table with - the name of the property. By convention the property name should end in "_fk". - - You are required to explicitly create foreign keys in order to allow for one-to-one, - one-to-many, and many-to-one relationships (but not for many-to-many relationships). If you do - not do so, SQLAlchemy will fail to create the relationship property and raise an exception with - a clear error message. - - You should normally not have to access this property directly, but instead use the associated - relationship properties. - - *This utility method should only be used during class creation.* - - :param other_table: other table name - :type other_table: basestring - :param nullable: ``True`` to allow null values (meaning that there is no relationship) - :type nullable: bool - """ - - return Column(Integer, - ForeignKey('{table}.id'.format(table=other_table), ondelete='CASCADE'), - nullable=nullable) - - -def one_to_one_self(model_class, fk): - """ - Declare a one-to-one relationship property. The property value would be an instance of the same - model. - - You will need an associated foreign key to our own table. - - *This utility method should only be used during class creation.* - - :param model_class: class in which this relationship will be declared - :type model_class: type - :param fk: foreign key name - :type fk: basestring - """ - - remote_side = '{model_class}.{remote_column}'.format( - model_class=model_class.__name__, - remote_column=model_class.id_column_name() - ) - - primaryjoin = '{remote_side} == {model_class}.{column}'.format( - remote_side=remote_side, - model_class=model_class.__name__, - column=fk - ) - return _relationship( - model_class, - model_class.__tablename__, - relationship_kwargs={ - 'primaryjoin': primaryjoin, - 'remote_side': remote_side, - 'post_update': True - } - ) - - -def one_to_one(model_class, - other_table, - fk=None, - other_fk=None, - back_populates=None): - """ - Declare a one-to-one relationship property. The property value would be an instance of the other - table's model. - - You have two options for the foreign key. Either this table can have an associated key to the - other table (use the ``fk`` argument) or the other table can have an associated foreign key to - this our table (use the ``other_fk`` argument). - - *This utility method should only be used during class creation.* - - :param model_class: class in which this relationship will be declared - :type model_class: type - :param other_table: other table name - :type other_table: basestring - :param fk: foreign key name at our table (no need specify if there's no ambiguity) - :type fk: basestring - :param other_fk: foreign key name at the other table (no need specify if there's no ambiguity) - :type other_fk: basestring - :param back_populates: override name of matching many-to-many property at other table; set to - ``False`` to disable - :type back_populates: basestring or bool - """ - backref_kwargs = None - if back_populates is not NO_BACK_POP: - if back_populates is None: - back_populates = model_class.__tablename__ - backref_kwargs = {'name': back_populates, 'uselist': False} - back_populates = None - - return _relationship(model_class, - other_table, - fk=fk, - back_populates=back_populates, - backref_kwargs=backref_kwargs, - other_fk=other_fk) - - -def one_to_many(model_class, - other_table=None, - other_fk=None, - dict_key=None, - back_populates=None, - rel_kwargs=None, - self=False): - """ - Declare a one-to-many relationship property. The property value would be a list or dict of - instances of the child table's model. - - The child table will need an associated foreign key to our table. - - The declaration will automatically create a matching many-to-one property at the child model, - named after our table name. Use the ``child_property`` argument to override this name. - - *This utility method should only be used during class creation.* - - :param model_class: class in which this relationship will be declared - :type model_class: type - :param other_table: other table name - :type other_table: basestring - :param other_fk: foreign key name at the other table (no need specify if there's no ambiguity) - :type other_fk: basestring - :param dict_key: if set the value will be a dict with this key as the dict key; otherwise will - be a list - :type dict_key: basestring - :param back_populates: override name of matching many-to-one property at other table; set to - ``False`` to disable - :type back_populates: basestring or bool - :param rel_kwargs: additional relationship kwargs to be used by SQLAlchemy - :type rel_kwargs: dict - :param self: used for relationships between a table and itself. if set, other_table will - become the same as the source table. - :type self: bool - """ - relationship_kwargs = rel_kwargs or {} - if self: - assert other_fk - other_table_name = model_class.__tablename__ - back_populates = False - relationship_kwargs['remote_side'] = '{model}.{column}'.format(model=model_class.__name__, - column=other_fk) - - else: - assert other_table - other_table_name = other_table - if back_populates is None: - back_populates = model_class.__tablename__ - relationship_kwargs.setdefault('cascade', 'all') - - return _relationship( - model_class, - other_table_name, - back_populates=back_populates, - other_fk=other_fk, - dict_key=dict_key, - relationship_kwargs=relationship_kwargs) - - -def many_to_one(model_class, - parent_table, - fk=None, - parent_fk=None, - back_populates=None): - """ - Declare a many-to-one relationship property. The property value would be an instance of the - parent table's model. - - You will need an associated foreign key to the parent table. - - The declaration will automatically create a matching one-to-many property at the child model, - named after the plural form of our table name. Use the ``parent_property`` argument to override - this name. Note: the automatic property will always be a SQLAlchemy query object; if you need a - Python collection then use :func:`one_to_many` at that model. - - *This utility method should only be used during class creation.* - - :param model_class: class in which this relationship will be declared - :type model_class: type - :param parent_table: parent table name - :type parent_table: basestring - :param fk: foreign key name at our table (no need specify if there's no ambiguity) - :type fk: basestring - :param back_populates: override name of matching one-to-many property at parent table; set to - ``False`` to disable - :type back_populates: basestring or bool - """ - if back_populates is None: - back_populates = formatting.pluralize(model_class.__tablename__) - - return _relationship(model_class, - parent_table, - back_populates=back_populates, - fk=fk, - other_fk=parent_fk) - - -def many_to_many(model_class, - other_table=None, - prefix=None, - dict_key=None, - other_property=None, - self=False): - """ - Declare a many-to-many relationship property. The property value would be a list or dict of - instances of the other table's model. - - You do not need associated foreign keys for this relationship. Instead, an extra table will be - created for you. - - The declaration will automatically create a matching many-to-many property at the other model, - named after the plural form of our table name. Use the ``other_property`` argument to override - this name. Note: the automatic property will always be a SQLAlchemy query object; if you need a - Python collection then use :func:`many_to_many` again at that model. - - *This utility method should only be used during class creation.* - - :param model_class: class in which this relationship will be declared - :type model_class: type - :param other_table: parent table name - :type other_table: basestring - :param prefix: optional prefix for extra table name as well as for ``other_property`` - :type prefix: basestring - :param dict_key: if set the value will be a dict with this key as the dict key; otherwise will - be a list - :type dict_key: basestring - :param other_property: override name of matching many-to-many property at other table; set to - ``False`` to disable - :type other_property: basestring or bool - :param self: used for relationships between a table and itself. if set, other_table will - become the same as the source table. - :type self: bool - """ - - this_table = model_class.__tablename__ - this_column_name = '{0}_id'.format(this_table) - this_foreign_key = '{0}.id'.format(this_table) - - if self: - other_table = this_table - - other_column_name = '{0}_{1}'.format(other_table, 'self_ref_id' if self else 'id') - other_foreign_key = '{0}.{1}'.format(other_table, 'id') - - secondary_table_name = '{0}_{1}'.format(this_table, other_table) - - if prefix is not None: - secondary_table_name = '{0}_{1}'.format(prefix, secondary_table_name) - if other_property is None: - other_property = '{0}_{1}'.format(prefix, formatting.pluralize(this_table)) - - secondary_table = _get_secondary_table( - model_class.metadata, - secondary_table_name, - this_column_name, - other_column_name, - this_foreign_key, - other_foreign_key - ) - - kwargs = {'relationship_kwargs': {'secondary': secondary_table}} - - if self: - kwargs['back_populates'] = NO_BACK_POP - kwargs['relationship_kwargs']['primaryjoin'] = \ - getattr(model_class, 'id') == getattr(secondary_table.c, this_column_name) - kwargs['relationship_kwargs']['secondaryjoin'] = \ - getattr(model_class, 'id') == getattr(secondary_table.c, other_column_name) - else: - kwargs['backref_kwargs'] = \ - {'name': other_property, 'uselist': True} if other_property else None - kwargs['dict_key'] = dict_key - - return _relationship(model_class, other_table, **kwargs) - - -def association_proxy(*args, **kwargs): - if 'type' in kwargs: - type_ = kwargs.get('type') - del kwargs['type'] - else: - type_ = ':obj:`basestring`' - proxy = original_association_proxy(*args, **kwargs) - proxy.__doc__ = """ - Internal. For use in SQLAlchemy queries. - - :type: {0} - """.format(type_) - return proxy - - -def _relationship(model_class, - other_table_name, - back_populates=None, - backref_kwargs=None, - relationship_kwargs=None, - fk=None, - other_fk=None, - dict_key=None): - relationship_kwargs = relationship_kwargs or {} - - if fk: - relationship_kwargs.setdefault( - 'foreign_keys', - lambda: getattr(_get_class_for_table(model_class, model_class.__tablename__), fk) - ) - - elif other_fk: - relationship_kwargs.setdefault( - 'foreign_keys', - lambda: getattr(_get_class_for_table(model_class, other_table_name), other_fk) - ) - - if dict_key: - relationship_kwargs.setdefault('collection_class', - attribute_mapped_collection(dict_key)) - - if backref_kwargs: - assert back_populates is None - return relationship( - lambda: _get_class_for_table(model_class, other_table_name), - backref=backref(**backref_kwargs), - **relationship_kwargs - ) - else: - if back_populates is not NO_BACK_POP: - relationship_kwargs['back_populates'] = back_populates - return relationship(lambda: _get_class_for_table(model_class, other_table_name), - **relationship_kwargs) - - -def _get_class_for_table(model_class, tablename): - if tablename in (model_class.__name__, model_class.__tablename__): - return model_class - - for table_cls in model_class._decl_class_registry.values(): - if tablename == getattr(table_cls, '__tablename__', None): - return table_cls - - raise ValueError('unknown table: {0}'.format(tablename)) - - -def _get_secondary_table(metadata, - name, - first_column, - second_column, - first_foreign_key, - second_foreign_key): - return Table( - name, - metadata, - Column(first_column, Integer, ForeignKey(first_foreign_key)), - Column(second_column, Integer, ForeignKey(second_foreign_key)) - ) http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/modeling/service_changes.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/modeling/service_changes.py b/apache-ariatosca-0.1.1/aria/modeling/service_changes.py deleted file mode 100644 index 061262a..0000000 --- a/apache-ariatosca-0.1.1/aria/modeling/service_changes.py +++ /dev/null @@ -1,253 +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. - -""" -ARIA modeling service changes module -""" - -# pylint: disable=no-self-argument, no-member, abstract-method - -from collections import namedtuple - -from sqlalchemy import ( - Column, - Text, - DateTime, - Enum, -) -from sqlalchemy.ext.declarative import declared_attr - -from .types import (List, Dict) -from .mixins import ModelMixin -from . import relationship - - -class ServiceUpdateBase(ModelMixin): - """ - Deployment update model representation. - """ - __tablename__ = 'service_update' - - __private_fields__ = ('service_fk', - 'execution_fk') - - created_at = Column(DateTime, nullable=False, index=True) - service_plan = Column(Dict, nullable=False) - service_update_nodes = Column(Dict) - service_update_service = Column(Dict) - service_update_node_templates = Column(List) - modified_entity_ids = Column(Dict) - state = Column(Text) - - # region association proxies - - @declared_attr - def execution_name(cls): - return relationship.association_proxy('execution', cls.name_column_name()) - - @declared_attr - def service_name(cls): - return relationship.association_proxy('service', cls.name_column_name()) - - # endregion - - # region one_to_one relationships - - # endregion - - # region one_to_many relationships - - @declared_attr - def steps(cls): - return relationship.one_to_many(cls, 'service_update_step') - - # endregion - - # region many_to_one relationships - - @declared_attr - def execution(cls): - return relationship.one_to_one(cls, 'execution', back_populates=relationship.NO_BACK_POP) - - @declared_attr - def service(cls): - return relationship.many_to_one(cls, 'service', back_populates='updates') - - # endregion - - # region foreign keys - - @declared_attr - def execution_fk(cls): - return relationship.foreign_key('execution', nullable=True) - - @declared_attr - def service_fk(cls): - return relationship.foreign_key('service') - - # endregion - - def to_dict(self, suppress_error=False, **kwargs): - dep_update_dict = super(ServiceUpdateBase, self).to_dict(suppress_error) #pylint: disable=no-member - # Taking care of the fact the DeploymentSteps are _BaseModels - dep_update_dict['steps'] = [step.to_dict() for step in self.steps] - return dep_update_dict - - -class ServiceUpdateStepBase(ModelMixin): - """ - Deployment update step model representation. - """ - - __tablename__ = 'service_update_step' - - __private_fields__ = ('service_update_fk',) - - _action_types = namedtuple('ACTION_TYPES', 'ADD, REMOVE, MODIFY') - ACTION_TYPES = _action_types(ADD='add', REMOVE='remove', MODIFY='modify') - - _entity_types = namedtuple( - 'ENTITY_TYPES', - 'NODE, RELATIONSHIP, PROPERTY, OPERATION, WORKFLOW, OUTPUT, DESCRIPTION, GROUP, PLUGIN') - ENTITY_TYPES = _entity_types( - NODE='node', - RELATIONSHIP='relationship', - PROPERTY='property', - OPERATION='operation', - WORKFLOW='workflow', - OUTPUT='output', - DESCRIPTION='description', - GROUP='group', - PLUGIN='plugin' - ) - - action = Column(Enum(*ACTION_TYPES, name='action_type'), nullable=False) - entity_id = Column(Text, nullable=False) - entity_type = Column(Enum(*ENTITY_TYPES, name='entity_type'), nullable=False) - - # region association proxies - - @declared_attr - def service_update_name(cls): - return relationship.association_proxy('service_update', cls.name_column_name()) - - # endregion - - # region one_to_one relationships - - # endregion - - # region one_to_many relationships - - # endregion - - # region many_to_one relationships - - @declared_attr - def service_update(cls): - return relationship.many_to_one(cls, 'service_update', back_populates='steps') - - # endregion - - # region foreign keys - - @declared_attr - def service_update_fk(cls): - return relationship.foreign_key('service_update') - - # endregion - - def __hash__(self): - return hash((getattr(self, self.id_column_name()), self.entity_id)) - - def __lt__(self, other): - """ - the order is 'remove' < 'modify' < 'add' - :param other: - :return: - """ - if not isinstance(other, self.__class__): - return not self >= other - - if self.action != other.action: - if self.action == 'remove': - return_value = True - elif self.action == 'add': - return_value = False - else: - return_value = other.action == 'add' - return return_value - - if self.action == 'add': - return self.entity_type == 'node' and other.entity_type == 'relationship' - if self.action == 'remove': - return self.entity_type == 'relationship' and other.entity_type == 'node' - return False - - -class ServiceModificationBase(ModelMixin): - """ - Deployment modification model representation. - """ - - __tablename__ = 'service_modification' - - __private_fields__ = ('service_fk',) - - STARTED = 'started' - FINISHED = 'finished' - ROLLEDBACK = 'rolledback' - - STATES = [STARTED, FINISHED, ROLLEDBACK] - END_STATES = [FINISHED, ROLLEDBACK] - - context = Column(Dict) - created_at = Column(DateTime, nullable=False, index=True) - ended_at = Column(DateTime, index=True) - modified_node_templates = Column(Dict) - nodes = Column(Dict) - status = Column(Enum(*STATES, name='service_modification_status')) - - # region association proxies - - @declared_attr - def service_name(cls): - return relationship.association_proxy('service', cls.name_column_name()) - - # endregion - - # region one_to_one relationships - - # endregion - - # region one_to_many relationships - - # endregion - - # region many_to_one relationships - - @declared_attr - def service(cls): - return relationship.many_to_one(cls, 'service', back_populates='modifications') - - # endregion - - # region foreign keys - - @declared_attr - def service_fk(cls): - return relationship.foreign_key('service') - - # endregion http://git-wip-us.apache.org/repos/asf/incubator-ariatosca-website/blob/23d6ba76/apache-ariatosca-0.1.1/aria/modeling/service_common.py ---------------------------------------------------------------------- diff --git a/apache-ariatosca-0.1.1/aria/modeling/service_common.py b/apache-ariatosca-0.1.1/aria/modeling/service_common.py deleted file mode 100644 index b533a88..0000000 --- a/apache-ariatosca-0.1.1/aria/modeling/service_common.py +++ /dev/null @@ -1,615 +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. - -""" -ARIA modeling service common module -""" - -# pylint: disable=no-self-argument, no-member, abstract-method - -from sqlalchemy import ( - Column, - Text, -) -from sqlalchemy.ext.declarative import declared_attr - -from ..parser.consumption import ConsumptionContext -from ..utils import ( - collections, - formatting, - console, -) -from .mixins import InstanceModelMixin, TemplateModelMixin, ParameterMixin -from . import relationship - - -class OutputBase(ParameterMixin): - """ - Output parameter or declaration for an output parameter. - """ - - __tablename__ = 'output' - - # region many_to_one relationships - - @declared_attr - def service_template(cls): - """ - Containing service template (can be ``None``). - - :type: :class:`ServiceTemplate` - """ - return relationship.many_to_one(cls, 'service_template') - - @declared_attr - def service(cls): - """ - Containing service (can be ``None``). - - :type: :class:`ServiceTemplate` - """ - return relationship.many_to_one(cls, 'service') - - # endregion - - # region foreign keys - - @declared_attr - def service_template_fk(cls): - return relationship.foreign_key('service_template', nullable=True) - - @declared_attr - def service_fk(cls): - return relationship.foreign_key('service', nullable=True) - - # endregion - - -class InputBase(ParameterMixin): - """ - Input parameter or declaration for an input parameter. - """ - - __tablename__ = 'input' - - # region many_to_one relationships - - @declared_attr - def service_template(cls): - """ - Containing service template (can be ``None``). - - :type: :class:`ServiceTemplate` - """ - return relationship.many_to_one(cls, 'service_template') - - @declared_attr - def service(cls): - """ - Containing service (can be ``None``). - - :type: :class:`Service` - """ - return relationship.many_to_one(cls, 'service') - - @declared_attr - def interface(cls): - """ - Containing interface (can be ``None``). - - :type: :class:`Interface` - """ - return relationship.many_to_one(cls, 'interface') - - @declared_attr - def operation(cls): - """ - Containing operation (can be ``None``). - - :type: :class:`Operation` - """ - return relationship.many_to_one(cls, 'operation') - - @declared_attr - def interface_template(cls): - """ - Containing interface template (can be ``None``). - - :type: :class:`InterfaceTemplate` - """ - return relationship.many_to_one(cls, 'interface_template') - - @declared_attr - def operation_template(cls): - """ - Containing operation template (can be ``None``). - - :type: :class:`OperationTemplate` - """ - return relationship.many_to_one(cls, 'operation_template') - - @declared_attr - def execution(cls): - """ - Containing execution (can be ``None``). - - :type: :class:`Execution` - """ - return relationship.many_to_one(cls, 'execution') - - # endregion - - # region foreign keys - - @declared_attr - def service_template_fk(cls): - return relationship.foreign_key('service_template', nullable=True) - - @declared_attr - def service_fk(cls): - return relationship.foreign_key('service', nullable=True) - - @declared_attr - def interface_fk(cls): - return relationship.foreign_key('interface', nullable=True) - - @declared_attr - def operation_fk(cls): - return relationship.foreign_key('operation', nullable=True) - - @declared_attr - def interface_template_fk(cls): - return relationship.foreign_key('interface_template', nullable=True) - - @declared_attr - def operation_template_fk(cls): - return relationship.foreign_key('operation_template', nullable=True) - - @declared_attr - def execution_fk(cls): - return relationship.foreign_key('execution', nullable=True) - - @declared_attr - def task_fk(cls): - return relationship.foreign_key('task', nullable=True) - - # endregion - - -class ConfigurationBase(ParameterMixin): - """ - Configuration parameter. - """ - - __tablename__ = 'configuration' - - # region many_to_one relationships - - @declared_attr - def operation_template(cls): - """ - Containing operation template (can be ``None``). - - :type: :class:`OperationTemplate` - """ - return relationship.many_to_one(cls, 'operation_template') - - @declared_attr - def operation(cls): - """ - Containing operation (can be ``None``). - - :type: :class:`Operation` - """ - return relationship.many_to_one(cls, 'operation') - - # endregion - - # region foreign keys - - @declared_attr - def operation_template_fk(cls): - return relationship.foreign_key('operation_template', nullable=True) - - @declared_attr - def operation_fk(cls): - return relationship.foreign_key('operation', nullable=True) - - # endregion - - -class PropertyBase(ParameterMixin): - """ - Property parameter or declaration for a property parameter. - """ - - __tablename__ = 'property' - - # region many_to_one relationships - - @declared_attr - def node_template(cls): - """ - Containing node template (can be ``None``). - - :type: :class:`NodeTemplate` - """ - return relationship.many_to_one(cls, 'node_template') - - @declared_attr - def group_template(cls): - """ - Containing group template (can be ``None``). - - :type: :class:`GroupTemplate` - """ - return relationship.many_to_one(cls, 'group_template') - - @declared_attr - def policy_template(cls): - """ - Containing policy template (can be ``None``). - - :type: :class:`PolicyTemplate` - """ - return relationship.many_to_one(cls, 'policy_template') - - @declared_attr - def relationship_template(cls): - """ - Containing relationship template (can be ``None``). - - :type: :class:`RelationshipTemplate` - """ - return relationship.many_to_one(cls, 'relationship_template') - - @declared_attr - def capability_template(cls): - """ - Containing capability template (can be ``None``). - - :type: :class:`CapabilityTemplate` - """ - return relationship.many_to_one(cls, 'capability_template') - - @declared_attr - def artifact_template(cls): - """ - Containing artifact template (can be ``None``). - - :type: :class:`ArtifactTemplate` - """ - return relationship.many_to_one(cls, 'artifact_template') - - @declared_attr - def node(cls): - """ - Containing node (can be ``None``). - - :type: :class:`Node` - """ - return relationship.many_to_one(cls, 'node') - - @declared_attr - def group(cls): - """ - Containing group (can be ``None``). - - :type: :class:`Group` - """ - return relationship.many_to_one(cls, 'group') - - @declared_attr - def policy(cls): - """ - Containing policy (can be ``None``). - - :type: :class:`Policy` - """ - return relationship.many_to_one(cls, 'policy') - - @declared_attr - def relationship(cls): - """ - Containing relationship (can be ``None``). - - :type: :class:`Relationship` - """ - return relationship.many_to_one(cls, 'relationship') - - @declared_attr - def capability(cls): - """ - Containing capability (can be ``None``). - - :type: :class:`Capability` - """ - return relationship.many_to_one(cls, 'capability') - - @declared_attr - def artifact(cls): - """ - Containing artifact (can be ``None``). - - :type: :class:`Artifact` - """ - return relationship.many_to_one(cls, 'artifact') - - # endregion - - # region foreign keys - - @declared_attr - def node_template_fk(cls): - return relationship.foreign_key('node_template', nullable=True) - - @declared_attr - def group_template_fk(cls): - return relationship.foreign_key('group_template', nullable=True) - - @declared_attr - def policy_template_fk(cls): - return relationship.foreign_key('policy_template', nullable=True) - - @declared_attr - def relationship_template_fk(cls): - return relationship.foreign_key('relationship_template', nullable=True) - - @declared_attr - def capability_template_fk(cls): - return relationship.foreign_key('capability_template', nullable=True) - - @declared_attr - def artifact_template_fk(cls): - return relationship.foreign_key('artifact_template', nullable=True) - - @declared_attr - def node_fk(cls): - return relationship.foreign_key('node', nullable=True) - - @declared_attr - def group_fk(cls): - return relationship.foreign_key('group', nullable=True) - - @declared_attr - def policy_fk(cls): - return relationship.foreign_key('policy', nullable=True) - - @declared_attr - def relationship_fk(cls): - return relationship.foreign_key('relationship', nullable=True) - - @declared_attr - def capability_fk(cls): - return relationship.foreign_key('capability', nullable=True) - - @declared_attr - def artifact_fk(cls): - return relationship.foreign_key('artifact', nullable=True) - - # endregion - - -class AttributeBase(ParameterMixin): - """ - Attribute parameter or declaration for an attribute parameter. - """ - - __tablename__ = 'attribute' - - # region many_to_one relationships - - @declared_attr - def node_template(cls): - """ - Containing node template (can be ``None``). - - :type: :class:`NodeTemplate` - """ - return relationship.many_to_one(cls, 'node_template') - - @declared_attr - def node(cls): - """ - Containing node (can be ``None``). - - :type: :class:`Node` - """ - return relationship.many_to_one(cls, 'node') - - # endregion - - # region foreign keys - - @declared_attr - def node_template_fk(cls): - """For Attribute many-to-one to NodeTemplate""" - return relationship.foreign_key('node_template', nullable=True) - - @declared_attr - def node_fk(cls): - """For Attribute many-to-one to Node""" - return relationship.foreign_key('node', nullable=True) - - # endregion - - -class TypeBase(InstanceModelMixin): - """ - Type and its children. Can serve as the root for a type hierarchy. - """ - - __tablename__ = 'type' - - __private_fields__ = ('parent_type_fk',) - - variant = Column(Text, nullable=False) - - description = Column(Text, doc=""" - Human-readable description. - - :type: :obj:`basestring` - """) - - _role = Column(Text, name='role') - - # region one_to_one relationships - - @declared_attr - def parent(cls): - """ - Parent type (will be ``None`` for the root of a type hierarchy). - - :type: :class:`Type` - """ - return relationship.one_to_one_self(cls, 'parent_type_fk') - - # endregion - - # region one_to_many relationships - - @declared_attr - def children(cls): - """ - Children. - - :type: [:class:`Type`] - """ - return relationship.one_to_many(cls, other_fk='parent_type_fk', self=True) - - # endregion - - # region foreign keys - - @declared_attr - def parent_type_fk(cls): - """For Type one-to-many to Type""" - return relationship.foreign_key('type', nullable=True) - - # endregion - - @property - def role(self): - def get_role(the_type): - if the_type is None: - return None - elif the_type._role is None: - return get_role(the_type.parent) - return the_type._role - - return get_role(self) - - @role.setter - def role(self, value): - self._role = value - - def is_descendant(self, base_name, name): - base = self.get_descendant(base_name) - if base is not None: - if base.get_descendant(name) is not None: - return True - return False - - def get_descendant(self, name): - if self.name == name: - return self - for child in self.children: - found = child.get_descendant(name) - if found is not None: - return found - return None - - def iter_descendants(self): - for child in self.children: - yield child - for descendant in child.iter_descendants(): - yield descendant - - @property - def as_raw(self): - return collections.OrderedDict(( - ('name', self.name), - ('description', self.description), - ('role', self.role))) - - @property - def as_raw_all(self): - types = [] - self._append_raw_children(types) - return types - - def coerce_values(self, report_issues): - pass - - def dump(self): - context = ConsumptionContext.get_thread_local() - if self.name: - console.puts(context.style.type(self.name)) - with context.style.indent: - for child in self.children: - child.dump() - - def _append_raw_children(self, types): - for child in self.children: - raw_child = formatting.as_raw(child) - raw_child['parent'] = self.name - types.append(raw_child) - child._append_raw_children(types) - - @property - def hierarchy(self): - """ - Type hierarchy as a list beginning with this type and ending in the root. - - :type: [:class:`Type`] - """ - return [self] + (self.parent.hierarchy if self.parent else []) - - -class MetadataBase(TemplateModelMixin): - """ - Custom values associated with the service. - - This model is used by both service template and service instance elements. - - :ivar name: name - :vartype name: basestring - :ivar value: value - :vartype value: basestring - """ - - __tablename__ = 'metadata' - - value = Column(Text) - - @property - def as_raw(self): - return collections.OrderedDict(( - ('name', self.name), - ('value', self.value))) - - def coerce_values(self, report_issues): - pass - - def instantiate(self, container): - from . import models - return models.Metadata(name=self.name, - value=self.value) - - def dump(self): - context = ConsumptionContext.get_thread_local() - console.puts('{0}: {1}'.format( - context.style.property(self.name), - context.style.literal(self.value)))
