You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@ariatosca.apache.org by mx...@apache.org on 2016/12/20 15:30:31 UTC
[1/4] incubator-ariatosca git commit: ARIA-31 Add registry mechanism
for extensions [Forced Update!]
Repository: incubator-ariatosca
Updated Branches:
refs/heads/ARIA-39-Genericize-storage-models 3cca6f5ed -> 6e1f1260f (forced update)
ARIA-31 Add registry mechanism for extensions
Project: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/commit/04c9bd07
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/tree/04c9bd07
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/diff/04c9bd07
Branch: refs/heads/ARIA-39-Genericize-storage-models
Commit: 04c9bd07916f957ddd88b933067266177a242a42
Parents: c6c92ae
Author: Dan Kilman <da...@gigaspaces.com>
Authored: Mon Dec 5 15:28:29 2016 +0200
Committer: Dan Kilman <da...@gigaspaces.com>
Committed: Sun Dec 11 19:26:28 2016 +0200
----------------------------------------------------------------------
aria/__init__.py | 25 +--
aria/cli/commands.py | 9 +-
aria/extension.py | 125 +++++++++++++++
aria/orchestrator/events.py | 36 +++++
aria/orchestrator/events/__init__.py | 57 -------
.../events/builtin_event_handler.py | 123 ---------------
.../events/workflow_engine_event_handler.py | 74 ---------
aria/orchestrator/workflows/__init__.py | 3 +
aria/orchestrator/workflows/core/engine.py | 2 +
.../workflows/core/events_handler.py | 113 ++++++++++++++
aria/orchestrator/workflows/events_logging.py | 65 ++++++++
aria/parser/__init__.py | 5 +-
aria/parser/loading/__init__.py | 3 +-
aria/parser/loading/uri.py | 5 +-
aria/parser/presentation/__init__.py | 3 +-
aria/parser/presentation/source.py | 7 +-
aria/parser/specification.py | 6 +-
aria/storage/structures.py | 4 +-
aria/utils/plugin.py | 39 -----
aria/utils/threading.py | 7 +-
extensions/aria_extension_tosca/__init__.py | 52 ++++---
.../simple_v1_0/data_types.py | 5 +-
requirements.txt | 1 +
tests/orchestrator/conftest.py | 23 +++
tests/orchestrator/events/__init__.py | 14 --
.../events/test_builtin_event_handlers.py | 14 --
.../test_workflow_enginge_event_handlers.py | 0
.../workflows/executor/test_executor.py | 16 +-
tests/test_extension.py | 156 +++++++++++++++++++
29 files changed, 602 insertions(+), 390 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/__init__.py
----------------------------------------------------------------------
diff --git a/aria/__init__.py b/aria/__init__.py
index b000397..0f7bec6 100644
--- a/aria/__init__.py
+++ b/aria/__init__.py
@@ -17,13 +17,18 @@
Aria top level package
"""
-import sys
import pkgutil
+try:
+ import pkg_resources
+except ImportError:
+ pkg_resources = None
+
from .VERSION import version as __version__
from .orchestrator.decorators import workflow, operation
from . import (
+ extension,
utils,
parser,
storage,
@@ -41,19 +46,17 @@ _resource_storage = {}
def install_aria_extensions():
"""
- Iterates all Python packages with names beginning with :code:`aria_extension_` and calls
- their :code:`install_aria_extension` function if they have it.
+ Iterates all Python packages with names beginning with :code:`aria_extension_` and all
+ :code:`aria_extension` entry points and loads them.
+ It then invokes all registered extension functions.
"""
-
for loader, module_name, _ in pkgutil.iter_modules():
if module_name.startswith('aria_extension_'):
- module = loader.find_module(module_name).load_module(module_name)
-
- if hasattr(module, 'install_aria_extension'):
- module.install_aria_extension()
-
- # Loading the module has contaminated sys.modules, so we'll clean it up
- del sys.modules[module_name]
+ loader.find_module(module_name).load_module(module_name)
+ if pkg_resources:
+ for entry_point in pkg_resources.iter_entry_points(group='aria_extension'):
+ entry_point.load()
+ extension.init()
def application_model_storage(api, api_kwargs=None):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/cli/commands.py
----------------------------------------------------------------------
diff --git a/aria/cli/commands.py b/aria/cli/commands.py
index 3426bb0..141da07 100644
--- a/aria/cli/commands.py
+++ b/aria/cli/commands.py
@@ -28,13 +28,14 @@ from importlib import import_module
from yaml import safe_load, YAMLError
+from .. import extension
from .. import (application_model_storage, application_resource_storage)
from ..logger import LoggerMixin
from ..storage import (FileSystemModelDriver, FileSystemResourceDriver)
from ..orchestrator.context.workflow import WorkflowContext
from ..orchestrator.workflows.core.engine import Engine
from ..orchestrator.workflows.executor.thread import ThreadExecutor
-from ..parser import (DSL_SPECIFICATION_PACKAGES, iter_specifications)
+from ..parser import iter_specifications
from ..parser.consumption import (
ConsumptionContext,
ConsumerChain,
@@ -45,7 +46,7 @@ from ..parser.consumption import (
Inputs,
Instance
)
-from ..parser.loading import (LiteralLocation, UriLocation, URI_LOADER_PREFIXES)
+from ..parser.loading import LiteralLocation, UriLocation
from ..utils.application import StorageManager
from ..utils.caching import cachedmethod
from ..utils.console import (puts, Colored, indent)
@@ -315,7 +316,7 @@ class ParseCommand(BaseCommand):
if args_namespace.prefix:
for prefix in args_namespace.prefix:
- URI_LOADER_PREFIXES.append(prefix)
+ extension.parser.uri_loader_prefix().append(prefix)
cachedmethod.ENABLED = args_namespace.cached_methods
@@ -376,7 +377,7 @@ class SpecCommand(BaseCommand):
super(SpecCommand, self).__call__(args_namespace, unknown_args)
# Make sure that all @dsl_specification decorators are processed
- for pkg in DSL_SPECIFICATION_PACKAGES:
+ for pkg in extension.parser.specification_package():
import_modules(pkg)
# TODO: scan YAML documents as well
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/extension.py
----------------------------------------------------------------------
diff --git a/aria/extension.py b/aria/extension.py
new file mode 100644
index 0000000..ddb7c25
--- /dev/null
+++ b/aria/extension.py
@@ -0,0 +1,125 @@
+# 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.
+
+# pylint: disable=no-self-use
+
+from .utils import collections
+
+
+class _Registrar(object):
+
+ def __init__(self, registry):
+ if not isinstance(registry, (dict, list)):
+ raise RuntimeError('Unsupported registry type')
+ self._registry = registry
+
+ def register(self, function):
+ result = function()
+ if isinstance(self._registry, dict):
+ for key in result:
+ if key in self._registry:
+ raise RuntimeError('Re-definition of {0} in {1}'.format(key, function.__name__))
+ self._registry.update(result)
+ elif isinstance(self._registry, list):
+ if not isinstance(result, (list, tuple, set)):
+ result = [result]
+ self._registry += list(result)
+ else:
+ raise RuntimeError('Illegal state')
+
+ def __call__(self):
+ return self._registry
+
+
+def _registrar(function):
+ function._registrar_function = True
+ return function
+
+
+class _ExtensionRegistration(object):
+ """Base class for extension class decorators"""
+
+ def __init__(self):
+ self._registrars = {}
+ self._registered_classes = []
+ for attr, value in vars(self.__class__).items():
+ try:
+ is_registrar_function = value._registrar_function
+ except AttributeError:
+ is_registrar_function = False
+ if is_registrar_function:
+ registrar = _Registrar(registry=getattr(self, attr)())
+ setattr(self, attr, registrar)
+ self._registrars[attr] = registrar
+
+ def __call__(self, cls):
+ self._registered_classes.append(cls)
+ return cls
+
+ def init(self):
+ """
+ Initialize all registrars by calling all registered functions
+ """
+ registered_instances = [cls() for cls in self._registered_classes]
+ for name, registrar in self._registrars.items():
+ for instance in registered_instances:
+ registrating_function = getattr(instance, name, None)
+ if registrating_function:
+ registrar.register(registrating_function)
+
+
+class _ParserExtensionRegistration(_ExtensionRegistration):
+ """Parser extensions class decorator"""
+
+ @_registrar
+ def presenter_class(self):
+ """
+ Presentation class registration.
+ Implementing functions can return a single class or a list/tuple of classes
+ """
+ return []
+
+ @_registrar
+ def specification_package(self):
+ """
+ Specification package registration.
+ Implementing functions can return a package name or a list/tuple of names
+ """
+ return []
+
+ @_registrar
+ def specification_url(self):
+ """
+ Specification URL registration.
+ Implementing functions should return a dictionary from names to URLs
+ """
+ return {}
+
+ @_registrar
+ def uri_loader_prefix(self):
+ """
+ URI loader prefix registration.
+ Implementing functions can return a single prefix or a list/tuple of prefixes
+ """
+ return collections.StrictList(value_class=basestring)
+
+parser = _ParserExtensionRegistration()
+
+
+def init():
+ """
+ Initialize all registrars by calling all registered functions
+ """
+ parser.init()
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/events.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/events.py b/aria/orchestrator/events.py
new file mode 100644
index 0000000..a1c4922
--- /dev/null
+++ b/aria/orchestrator/events.py
@@ -0,0 +1,36 @@
+# 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's events Sub-Package
+Path: aria.events
+
+Events package provides events mechanism for different executions in aria.
+"""
+
+from blinker import signal
+
+# workflow engine task signals:
+sent_task_signal = signal('sent_task_signal')
+start_task_signal = signal('start_task_signal')
+on_success_task_signal = signal('success_task_signal')
+on_failure_task_signal = signal('failure_task_signal')
+
+# workflow engine workflow signals:
+start_workflow_signal = signal('start_workflow_signal')
+on_cancelling_workflow_signal = signal('on_cancelling_workflow_signal')
+on_cancelled_workflow_signal = signal('on_cancelled_workflow_signal')
+on_success_workflow_signal = signal('on_success_workflow_signal')
+on_failure_workflow_signal = signal('on_failure_workflow_signal')
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/events/__init__.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/events/__init__.py b/aria/orchestrator/events/__init__.py
deleted file mode 100644
index fbc0f32..0000000
--- a/aria/orchestrator/events/__init__.py
+++ /dev/null
@@ -1,57 +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's events Sub-Package
-Path: aria.events
-
-Events package provides events mechanism for different executions in aria.
-
-
-1. storage_event_handler: implementation of storage handlers for workflow and operation events.
-2. logger_event_handler: implementation of logger handlers for workflow and operation events.
-
-API:
- * start_task_signal
- * on_success_task_signal
- * on_failure_task_signal
- * start_workflow_signal
- * on_success_workflow_signal
- * on_failure_workflow_signal
-"""
-
-import os
-
-from blinker import signal
-
-from aria.utils.plugin import plugin_installer
-
-# workflow engine task signals:
-sent_task_signal = signal('sent_task_signal')
-start_task_signal = signal('start_task_signal')
-on_success_task_signal = signal('success_task_signal')
-on_failure_task_signal = signal('failure_task_signal')
-
-# workflow engine workflow signals:
-start_workflow_signal = signal('start_workflow_signal')
-on_cancelling_workflow_signal = signal('on_cancelling_workflow_signal')
-on_cancelled_workflow_signal = signal('on_cancelled_workflow_signal')
-on_success_workflow_signal = signal('on_success_workflow_signal')
-on_failure_workflow_signal = signal('on_failure_workflow_signal')
-
-plugin_installer(
- path=os.path.dirname(os.path.realpath(__file__)),
- plugin_suffix='_event_handler',
- package=__package__)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/events/builtin_event_handler.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/events/builtin_event_handler.py b/aria/orchestrator/events/builtin_event_handler.py
deleted file mode 100644
index c5cccfe..0000000
--- a/aria/orchestrator/events/builtin_event_handler.py
+++ /dev/null
@@ -1,123 +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's events Sub-Package
-Path: aria.events.storage_event_handler
-
-Implementation of storage handlers for workflow and operation events.
-"""
-
-
-from datetime import (
- datetime,
- timedelta,
-)
-
-from . import (
- start_workflow_signal,
- on_success_workflow_signal,
- on_failure_workflow_signal,
- on_cancelled_workflow_signal,
- on_cancelling_workflow_signal,
- sent_task_signal,
- start_task_signal,
- on_success_task_signal,
- on_failure_task_signal,
-)
-
-
-@sent_task_signal.connect
-def _task_sent(task, *args, **kwargs):
- with task._update():
- task.status = task.SENT
-
-
-@start_task_signal.connect
-def _task_started(task, *args, **kwargs):
- with task._update():
- task.started_at = datetime.utcnow()
- task.status = task.STARTED
-
-
-@on_failure_task_signal.connect
-def _task_failed(task, *args, **kwargs):
- with task._update():
- should_retry = (
- (task.retry_count < task.max_attempts - 1 or
- task.max_attempts == task.INFINITE_RETRIES) and
- # ignore_failure check here means the task will not be retries and it will be marked as
- # failed. The engine will also look at ignore_failure so it won't fail the workflow.
- not task.ignore_failure)
- if should_retry:
- task.status = task.RETRYING
- task.retry_count += 1
- task.due_at = datetime.utcnow() + timedelta(seconds=task.retry_interval)
- else:
- task.ended_at = datetime.utcnow()
- task.status = task.FAILED
-
-
-@on_success_task_signal.connect
-def _task_succeeded(task, *args, **kwargs):
- with task._update():
- task.ended_at = datetime.utcnow()
- task.status = task.SUCCESS
-
-
-@start_workflow_signal.connect
-def _workflow_started(workflow_context, *args, **kwargs):
- execution = workflow_context.execution
- execution.status = execution.STARTED
- execution.started_at = datetime.utcnow()
- workflow_context.execution = execution
-
-
-@on_failure_workflow_signal.connect
-def _workflow_failed(workflow_context, exception, *args, **kwargs):
- execution = workflow_context.execution
- execution.error = str(exception)
- execution.status = execution.FAILED
- execution.ended_at = datetime.utcnow()
- workflow_context.execution = execution
-
-
-@on_success_workflow_signal.connect
-def _workflow_succeeded(workflow_context, *args, **kwargs):
- execution = workflow_context.execution
- execution.status = execution.TERMINATED
- execution.ended_at = datetime.utcnow()
- workflow_context.execution = execution
-
-
-@on_cancelled_workflow_signal.connect
-def _workflow_cancelled(workflow_context, *args, **kwargs):
- execution = workflow_context.execution
- # _workflow_cancelling function may have called this function
- # already
- if execution.status == execution.CANCELLED:
- return
- execution.status = execution.CANCELLED
- execution.ended_at = datetime.utcnow()
- workflow_context.execution = execution
-
-
-@on_cancelling_workflow_signal.connect
-def _workflow_cancelling(workflow_context, *args, **kwargs):
- execution = workflow_context.execution
- if execution.status == execution.PENDING:
- return _workflow_cancelled(workflow_context=workflow_context)
- execution.status = execution.CANCELLING
- workflow_context.execution = execution
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/events/workflow_engine_event_handler.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/events/workflow_engine_event_handler.py b/aria/orchestrator/events/workflow_engine_event_handler.py
deleted file mode 100644
index 7df11d1..0000000
--- a/aria/orchestrator/events/workflow_engine_event_handler.py
+++ /dev/null
@@ -1,74 +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's events Sub-Package
-Path: aria.events.storage_event_handler
-
-Implementation of logger handlers for workflow and operation events.
-"""
-
-from . import (
- start_task_signal,
- on_success_task_signal,
- on_failure_task_signal,
- start_workflow_signal,
- on_success_workflow_signal,
- on_failure_workflow_signal,
- on_cancelled_workflow_signal,
- on_cancelling_workflow_signal,
-)
-
-
-@start_task_signal.connect
-def _start_task_handler(task, **kwargs):
- task.logger.debug('Event: Starting task: {task.name}'.format(task=task))
-
-
-@on_success_task_signal.connect
-def _success_task_handler(task, **kwargs):
- task.logger.debug('Event: Task success: {task.name}'.format(task=task))
-
-
-@on_failure_task_signal.connect
-def _failure_operation_handler(task, **kwargs):
- task.logger.error('Event: Task failure: {task.name}'.format(task=task),
- exc_info=kwargs.get('exception', True))
-
-
-@start_workflow_signal.connect
-def _start_workflow_handler(context, **kwargs):
- context.logger.debug('Event: Starting workflow: {context.name}'.format(context=context))
-
-
-@on_failure_workflow_signal.connect
-def _failure_workflow_handler(context, **kwargs):
- context.logger.debug('Event: Workflow failure: {context.name}'.format(context=context))
-
-
-@on_success_workflow_signal.connect
-def _success_workflow_handler(context, **kwargs):
- context.logger.debug('Event: Workflow success: {context.name}'.format(context=context))
-
-
-@on_cancelled_workflow_signal.connect
-def _cancel_workflow_handler(context, **kwargs):
- context.logger.debug('Event: Workflow cancelled: {context.name}'.format(context=context))
-
-
-@on_cancelling_workflow_signal.connect
-def _cancelling_workflow_handler(context, **kwargs):
- context.logger.debug('Event: Workflow cancelling: {context.name}'.format(context=context))
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/workflows/__init__.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/__init__.py b/aria/orchestrator/workflows/__init__.py
index ae1e83e..e0c979a 100644
--- a/aria/orchestrator/workflows/__init__.py
+++ b/aria/orchestrator/workflows/__init__.py
@@ -12,3 +12,6 @@
# 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.
+
+# Import required so that logging signals are registered
+from . import events_logging
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/workflows/core/engine.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/core/engine.py b/aria/orchestrator/workflows/core/engine.py
index 2d26aeb..7886b7a 100644
--- a/aria/orchestrator/workflows/core/engine.py
+++ b/aria/orchestrator/workflows/core/engine.py
@@ -29,6 +29,8 @@ from aria.orchestrator import events
from .. import exceptions
from . import task as engine_task
from . import translation
+# Import required so all signals are registered
+from . import events_handler # pylint: disable=unused-import
class Engine(logger.LoggerMixin):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/workflows/core/events_handler.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/core/events_handler.py b/aria/orchestrator/workflows/core/events_handler.py
new file mode 100644
index 0000000..d05cbcb
--- /dev/null
+++ b/aria/orchestrator/workflows/core/events_handler.py
@@ -0,0 +1,113 @@
+# 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's events Sub-Package
+Path: aria.events.storage_event_handler
+
+Implementation of storage handlers for workflow and operation events.
+"""
+
+
+from datetime import (
+ datetime,
+ timedelta,
+)
+
+from ... import events
+
+
+@events.sent_task_signal.connect
+def _task_sent(task, *args, **kwargs):
+ with task._update():
+ task.status = task.SENT
+
+
+@events.start_task_signal.connect
+def _task_started(task, *args, **kwargs):
+ with task._update():
+ task.started_at = datetime.utcnow()
+ task.status = task.STARTED
+
+
+@events.on_failure_task_signal.connect
+def _task_failed(task, *args, **kwargs):
+ with task._update():
+ should_retry = (
+ (task.retry_count < task.max_attempts - 1 or
+ task.max_attempts == task.INFINITE_RETRIES) and
+ # ignore_failure check here means the task will not be retries and it will be marked as
+ # failed. The engine will also look at ignore_failure so it won't fail the workflow.
+ not task.ignore_failure)
+ if should_retry:
+ task.status = task.RETRYING
+ task.retry_count += 1
+ task.due_at = datetime.utcnow() + timedelta(seconds=task.retry_interval)
+ else:
+ task.ended_at = datetime.utcnow()
+ task.status = task.FAILED
+
+
+@events.on_success_task_signal.connect
+def _task_succeeded(task, *args, **kwargs):
+ with task._update():
+ task.ended_at = datetime.utcnow()
+ task.status = task.SUCCESS
+
+
+@events.start_workflow_signal.connect
+def _workflow_started(workflow_context, *args, **kwargs):
+ execution = workflow_context.execution
+ execution.status = execution.STARTED
+ execution.started_at = datetime.utcnow()
+ workflow_context.execution = execution
+
+
+@events.on_failure_workflow_signal.connect
+def _workflow_failed(workflow_context, exception, *args, **kwargs):
+ execution = workflow_context.execution
+ execution.error = str(exception)
+ execution.status = execution.FAILED
+ execution.ended_at = datetime.utcnow()
+ workflow_context.execution = execution
+
+
+@events.on_success_workflow_signal.connect
+def _workflow_succeeded(workflow_context, *args, **kwargs):
+ execution = workflow_context.execution
+ execution.status = execution.TERMINATED
+ execution.ended_at = datetime.utcnow()
+ workflow_context.execution = execution
+
+
+@events.on_cancelled_workflow_signal.connect
+def _workflow_cancelled(workflow_context, *args, **kwargs):
+ execution = workflow_context.execution
+ # _workflow_cancelling function may have called this function
+ # already
+ if execution.status == execution.CANCELLED:
+ return
+ execution.status = execution.CANCELLED
+ execution.ended_at = datetime.utcnow()
+ workflow_context.execution = execution
+
+
+@events.on_cancelling_workflow_signal.connect
+def _workflow_cancelling(workflow_context, *args, **kwargs):
+ execution = workflow_context.execution
+ if execution.status == execution.PENDING:
+ return _workflow_cancelled(workflow_context=workflow_context)
+ execution.status = execution.CANCELLING
+ workflow_context.execution = execution
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/orchestrator/workflows/events_logging.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/events_logging.py b/aria/orchestrator/workflows/events_logging.py
new file mode 100644
index 0000000..409ce0a
--- /dev/null
+++ b/aria/orchestrator/workflows/events_logging.py
@@ -0,0 +1,65 @@
+# 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's events Sub-Package
+Path: aria.events.storage_event_handler
+
+Implementation of logger handlers for workflow and operation events.
+"""
+
+from .. import events
+
+
+@events.start_task_signal.connect
+def _start_task_handler(task, **kwargs):
+ task.logger.debug('Event: Starting task: {task.name}'.format(task=task))
+
+
+@events.on_success_task_signal.connect
+def _success_task_handler(task, **kwargs):
+ task.logger.debug('Event: Task success: {task.name}'.format(task=task))
+
+
+@events.on_failure_task_signal.connect
+def _failure_operation_handler(task, **kwargs):
+ task.logger.error('Event: Task failure: {task.name}'.format(task=task),
+ exc_info=kwargs.get('exception', True))
+
+
+@events.start_workflow_signal.connect
+def _start_workflow_handler(context, **kwargs):
+ context.logger.debug('Event: Starting workflow: {context.name}'.format(context=context))
+
+
+@events.on_failure_workflow_signal.connect
+def _failure_workflow_handler(context, **kwargs):
+ context.logger.debug('Event: Workflow failure: {context.name}'.format(context=context))
+
+
+@events.on_success_workflow_signal.connect
+def _success_workflow_handler(context, **kwargs):
+ context.logger.debug('Event: Workflow success: {context.name}'.format(context=context))
+
+
+@events.on_cancelled_workflow_signal.connect
+def _cancel_workflow_handler(context, **kwargs):
+ context.logger.debug('Event: Workflow cancelled: {context.name}'.format(context=context))
+
+
+@events.on_cancelling_workflow_signal.connect
+def _cancelling_workflow_handler(context, **kwargs):
+ context.logger.debug('Event: Workflow cancelling: {context.name}'.format(context=context))
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/__init__.py
----------------------------------------------------------------------
diff --git a/aria/parser/__init__.py b/aria/parser/__init__.py
index 2a83cd4..9ab8785 100644
--- a/aria/parser/__init__.py
+++ b/aria/parser/__init__.py
@@ -13,8 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from .specification import (DSL_SPECIFICATION_PACKAGES, DSL_SPECIFICATION_URLS, dsl_specification,
- iter_specifications)
+from .specification import dsl_specification, iter_specifications
MODULES = (
@@ -27,7 +26,5 @@ MODULES = (
__all__ = (
'MODULES',
- 'DSL_SPECIFICATION_PACKAGES',
- 'DSL_SPECIFICATION_URLS',
'dsl_specification',
'iter_specifications')
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/loading/__init__.py
----------------------------------------------------------------------
diff --git a/aria/parser/loading/__init__.py b/aria/parser/loading/__init__.py
index f331e39..006f164 100644
--- a/aria/parser/loading/__init__.py
+++ b/aria/parser/loading/__init__.py
@@ -20,7 +20,7 @@ from .loader import Loader
from .source import LoaderSource, DefaultLoaderSource
from .location import Location, UriLocation, LiteralLocation
from .literal import LiteralLoader
-from .uri import URI_LOADER_PREFIXES, UriTextLoader
+from .uri import UriTextLoader
from .request import SESSION, SESSION_CACHE_PATH, RequestLoader, RequestTextLoader
from .file import FileTextLoader
@@ -37,7 +37,6 @@ __all__ = (
'UriLocation',
'LiteralLocation',
'LiteralLoader',
- 'URI_LOADER_PREFIXES',
'UriTextLoader',
'SESSION',
'SESSION_CACHE_PATH',
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/loading/uri.py
----------------------------------------------------------------------
diff --git a/aria/parser/loading/uri.py b/aria/parser/loading/uri.py
index f94a003..f0cde3a 100644
--- a/aria/parser/loading/uri.py
+++ b/aria/parser/loading/uri.py
@@ -16,6 +16,7 @@
import os
from urlparse import urljoin
+from ...extension import parser
from ...utils.collections import StrictList
from ...utils.uris import as_file
from .loader import Loader
@@ -23,8 +24,6 @@ from .file import FileTextLoader
from .request import RequestTextLoader
from .exceptions import DocumentNotFoundException
-URI_LOADER_PREFIXES = StrictList(value_class=basestring)
-
class UriTextLoader(Loader):
"""
@@ -58,7 +57,7 @@ class UriTextLoader(Loader):
add_prefix(origin_location.prefix)
add_prefixes(context.prefixes)
- add_prefixes(URI_LOADER_PREFIXES)
+ add_prefixes(parser.uri_loader_prefix())
def open(self):
try:
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/presentation/__init__.py
----------------------------------------------------------------------
diff --git a/aria/parser/presentation/__init__.py b/aria/parser/presentation/__init__.py
index ba7a163..a681695 100644
--- a/aria/parser/presentation/__init__.py
+++ b/aria/parser/presentation/__init__.py
@@ -18,7 +18,7 @@ from .exceptions import PresenterException, PresenterNotFoundError
from .context import PresentationContext
from .presenter import Presenter
from .presentation import Value, PresentationBase, Presentation, AsIsPresentation
-from .source import PRESENTER_CLASSES, PresenterSource, DefaultPresenterSource
+from .source import PresenterSource, DefaultPresenterSource
from .null import NULL, none_to_null, null_to_none
from .fields import (Field, has_fields, short_form_field, allow_unknown_fields, primitive_field,
primitive_list_field, primitive_dict_field, primitive_dict_unknown_fields,
@@ -42,7 +42,6 @@ __all__ = (
'Presentation',
'AsIsPresentation',
'PresenterSource',
- 'PRESENTER_CLASSES',
'DefaultPresenterSource',
'NULL',
'none_to_null',
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/presentation/source.py
----------------------------------------------------------------------
diff --git a/aria/parser/presentation/source.py b/aria/parser/presentation/source.py
index 8ff4cab..7198b07 100644
--- a/aria/parser/presentation/source.py
+++ b/aria/parser/presentation/source.py
@@ -13,9 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from .exceptions import PresenterNotFoundError
-PRESENTER_CLASSES = []
+from ...extension import parser
+
+from .exceptions import PresenterNotFoundError
class PresenterSource(object):
@@ -36,7 +37,7 @@ class DefaultPresenterSource(PresenterSource):
def __init__(self, classes=None):
if classes is None:
- classes = PRESENTER_CLASSES
+ classes = parser.presenter_class()
self.classes = classes
def get_presenter(self, raw):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/parser/specification.py
----------------------------------------------------------------------
diff --git a/aria/parser/specification.py b/aria/parser/specification.py
index 1c7e1f2..1df11ce 100644
--- a/aria/parser/specification.py
+++ b/aria/parser/specification.py
@@ -15,12 +15,10 @@
import re
+from ..extension import parser
from ..utils.collections import OrderedDict
from ..utils.formatting import full_type_name
-
-DSL_SPECIFICATION_PACKAGES = []
-DSL_SPECIFICATION_URLS = {}
_DSL_SPECIFICATIONS = {}
@@ -84,7 +82,7 @@ def _section_key(value):
def _fix_details(details, spec):
code = details.get('code')
doc = details.get('doc')
- url = DSL_SPECIFICATION_URLS.get(spec)
+ url = parser.specification_url().get(spec)
if (url is not None) and (doc is not None):
# Look for a URL in ReST docstring that begins with our url
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/storage/structures.py
----------------------------------------------------------------------
diff --git a/aria/storage/structures.py b/aria/storage/structures.py
index 8dbd2a9..8afa40c 100644
--- a/aria/storage/structures.py
+++ b/aria/storage/structures.py
@@ -106,11 +106,11 @@ class _MutableType(TypeDecorator):
def python_type(self):
raise NotImplementedError
+ impl = VARCHAR
+
def process_literal_param(self, value, dialect):
pass
- impl = VARCHAR
-
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/utils/plugin.py
----------------------------------------------------------------------
diff --git a/aria/utils/plugin.py b/aria/utils/plugin.py
deleted file mode 100644
index bb2b974..0000000
--- a/aria/utils/plugin.py
+++ /dev/null
@@ -1,39 +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.
-
-"""
-Contains utility methods that enable dynamic python code loading
-# TODO: merge with tools.module
-"""
-
-import os
-from importlib import import_module
-
-
-def plugin_installer(path, plugin_suffix, package=None, callback=None):
- """
- Load each module under ``path`` that ends with ``plugin_suffix``. If ``callback`` is supplied,
- call it with each loaded module.
- """
- assert callback is None or callable(callback)
- plugin_suffix = '{0}.py'.format(plugin_suffix)
-
- for file_name in os.listdir(path):
- if not file_name.endswith(plugin_suffix):
- continue
- module_name = '{0}.{1}'.format(package, file_name[:-3]) if package else file_name[:-3]
- module = import_module(module_name)
- if callback:
- callback(module)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/aria/utils/threading.py
----------------------------------------------------------------------
diff --git a/aria/utils/threading.py b/aria/utils/threading.py
index 575d011..b99250d 100644
--- a/aria/utils/threading.py
+++ b/aria/utils/threading.py
@@ -90,7 +90,7 @@ class FixedThreadPoolExecutor(object):
_CYANIDE = object() # Special task marker used to kill worker threads.
def __init__(self,
- size=multiprocessing.cpu_count() * 2 + 1,
+ size=None,
timeout=None,
print_exceptions=False):
"""
@@ -100,6 +100,11 @@ class FixedThreadPoolExecutor(object):
:param print_exceptions: Set to true in order to
print exceptions from tasks. (Defaults to false)
"""
+ if not size:
+ try:
+ size = multiprocessing.cpu_count() * 2 + 1
+ except NotImplementedError:
+ size = 3
self.size = size
self.timeout = timeout
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/extensions/aria_extension_tosca/__init__.py
----------------------------------------------------------------------
diff --git a/extensions/aria_extension_tosca/__init__.py b/extensions/aria_extension_tosca/__init__.py
index 54e1c84..d93dce2 100644
--- a/extensions/aria_extension_tosca/__init__.py
+++ b/extensions/aria_extension_tosca/__init__.py
@@ -15,34 +15,38 @@
import os.path
-from aria.parser import (DSL_SPECIFICATION_PACKAGES, DSL_SPECIFICATION_URLS)
-from aria.parser.presentation import PRESENTER_CLASSES
-from aria.parser.loading import URI_LOADER_PREFIXES
+from aria import extension
from .simple_v1_0 import ToscaSimplePresenter1_0
from .simple_nfv_v1_0 import ToscaSimpleNfvPresenter1_0
-def install_aria_extension():
- '''
- Installs the TOSCA extension to ARIA.
- '''
-
- global PRESENTER_CLASSES # pylint: disable=global-statement
- PRESENTER_CLASSES += (ToscaSimplePresenter1_0, ToscaSimpleNfvPresenter1_0)
-
- # DSL specification
- DSL_SPECIFICATION_PACKAGES.append('aria_extension_tosca')
- DSL_SPECIFICATION_URLS['yaml-1.1'] = \
- 'http://yaml.org'
- DSL_SPECIFICATION_URLS['tosca-simple-1.0'] = \
- 'http://docs.oasis-open.org/tosca/TOSCA-Simple-Profile-YAML/v1.0/cos01' \
- '/TOSCA-Simple-Profile-YAML-v1.0-cos01.html'
- DSL_SPECIFICATION_URLS['tosca-simple-nfv-1.0'] = \
- 'http://docs.oasis-open.org/tosca/tosca-nfv/v1.0/tosca-nfv-v1.0.html'
-
- # Imports
- the_dir = os.path.dirname(__file__)
- URI_LOADER_PREFIXES.append(os.path.join(the_dir, 'profiles'))
+
+@extension.parser
+class ParserExtensions(object):
+
+ @staticmethod
+ def presenter_class():
+ return ToscaSimplePresenter1_0, ToscaSimpleNfvPresenter1_0
+
+ @staticmethod
+ def specification_package():
+ return 'aria_extension_tosca'
+
+ @staticmethod
+ def specification_url():
+ return {
+ 'yaml-1.1': 'http://yaml.org',
+ 'tosca-simple-1.0': 'http://docs.oasis-open.org/tosca/TOSCA-Simple-Profile-YAML/v1.0/'
+ 'cos01/TOSCA-Simple-Profile-YAML-v1.0-cos01.html',
+ 'tosca-simple-nfv-1.0': 'http://docs.oasis-open.org/tosca/tosca-nfv/v1.0/'
+ 'tosca-nfv-v1.0.html'
+ }
+
+ @staticmethod
+ def uri_loader_prefix():
+ the_dir = os.path.dirname(__file__)
+ return os.path.join(the_dir, 'profiles')
+
MODULES = (
'simple_v1_0',
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/extensions/aria_extension_tosca/simple_v1_0/data_types.py
----------------------------------------------------------------------
diff --git a/extensions/aria_extension_tosca/simple_v1_0/data_types.py b/extensions/aria_extension_tosca/simple_v1_0/data_types.py
index 1fdbe6e..a06834c 100644
--- a/extensions/aria_extension_tosca/simple_v1_0/data_types.py
+++ b/extensions/aria_extension_tosca/simple_v1_0/data_types.py
@@ -14,8 +14,11 @@
# limitations under the License.
import re
-from functools import total_ordering
from datetime import datetime, tzinfo, timedelta
+try:
+ from functools import total_ordering
+except ImportError:
+ from total_ordering import total_ordering
from aria.parser import dsl_specification
from aria.utils.collections import StrictDict, OrderedDict
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/requirements.txt
----------------------------------------------------------------------
diff --git a/requirements.txt b/requirements.txt
index 7e87c67..31b0b79 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -17,6 +17,7 @@ retrying==1.3.3
blinker==1.4
importlib==1.0.4 ; python_version < '2.7'
ordereddict==1.1 ; python_version < '2.7'
+total-ordering==0.1.0 ; python_version < '2.7'
jsonpickle
ruamel.yaml==0.11.15
Jinja2==2.8
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/orchestrator/conftest.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/conftest.py b/tests/orchestrator/conftest.py
new file mode 100644
index 0000000..4b24f18
--- /dev/null
+++ b/tests/orchestrator/conftest.py
@@ -0,0 +1,23 @@
+# 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.
+
+import pytest
+
+import aria
+
+
+@pytest.fixture(scope='session', autouse=True)
+def install_aria_extensions():
+ aria.install_aria_extensions()
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/orchestrator/events/__init__.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/events/__init__.py b/tests/orchestrator/events/__init__.py
deleted file mode 100644
index ae1e83e..0000000
--- a/tests/orchestrator/events/__init__.py
+++ /dev/null
@@ -1,14 +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.
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/orchestrator/events/test_builtin_event_handlers.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/events/test_builtin_event_handlers.py b/tests/orchestrator/events/test_builtin_event_handlers.py
deleted file mode 100644
index ae1e83e..0000000
--- a/tests/orchestrator/events/test_builtin_event_handlers.py
+++ /dev/null
@@ -1,14 +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.
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/orchestrator/events/test_workflow_enginge_event_handlers.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/events/test_workflow_enginge_event_handlers.py b/tests/orchestrator/events/test_workflow_enginge_event_handlers.py
deleted file mode 100644
index e69de29..0000000
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/orchestrator/workflows/executor/test_executor.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/executor/test_executor.py b/tests/orchestrator/workflows/executor/test_executor.py
index a425799..654542c 100644
--- a/tests/orchestrator/workflows/executor/test_executor.py
+++ b/tests/orchestrator/workflows/executor/test_executor.py
@@ -20,6 +20,14 @@ from contextlib import contextmanager
import pytest
import retrying
+try:
+ import celery as _celery
+ app = _celery.Celery()
+ app.conf.update(CELERY_RESULT_BACKEND='amqp://')
+except ImportError:
+ _celery = None
+ app = None
+
from aria.storage import models
from aria.orchestrator import events
from aria.orchestrator.workflows.executor import (
@@ -29,14 +37,6 @@ from aria.orchestrator.workflows.executor import (
# celery
)
-try:
- import celery as _celery
- app = _celery.Celery()
- app.conf.update(CELERY_RESULT_BACKEND='amqp://')
-except ImportError:
- _celery = None
- app = None
-
class TestExecutor(object):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/04c9bd07/tests/test_extension.py
----------------------------------------------------------------------
diff --git a/tests/test_extension.py b/tests/test_extension.py
new file mode 100644
index 0000000..f0378fd
--- /dev/null
+++ b/tests/test_extension.py
@@ -0,0 +1,156 @@
+# 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.
+
+import pytest
+
+from aria import extension
+
+# #pylint: disable=no-member,no-method-argument,unused-variable
+
+
+class TestRegistrar(object):
+
+ def test_list_based_registrar_with_single_element_registration(self):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def list_based_registrar(*_):
+ return []
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension(object):
+ def list_based_registrar(self):
+ return True
+
+ assert extension_registration.list_based_registrar() == []
+ extension_registration.init()
+ assert extension_registration.list_based_registrar() == [True]
+
+ def test_list_based_registrar_with_sequence_element_registration(self):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def list_based_registrar1(*_):
+ return []
+
+ @extension._registrar
+ def list_based_registrar2(*_):
+ return []
+
+ @extension._registrar
+ def list_based_registrar3(*_):
+ return []
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension(object):
+ def list_based_registrar1(*_):
+ return [True, True]
+
+ def list_based_registrar2(*_):
+ return True, True
+
+ def list_based_registrar3(*_):
+ return set([True])
+
+ extension_registration.init()
+ assert extension_registration.list_based_registrar1() == [True, True]
+ assert extension_registration.list_based_registrar2() == [True, True]
+ assert extension_registration.list_based_registrar3() == [True]
+
+ def test_dict_based_registrar(self):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def dict_based_registrar(*_):
+ return {}
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension1(object):
+ def dict_based_registrar(self):
+ return {
+ 'a': 'a',
+ 'b': 'b'
+ }
+
+ @extension_registration
+ class Extension2(object):
+ def dict_based_registrar(self):
+ return {
+ 'c': 'c',
+ 'd': 'd'
+ }
+
+ assert extension_registration.dict_based_registrar() == {}
+ extension_registration.init()
+ assert extension_registration.dict_based_registrar() == {
+ 'a': 'a',
+ 'b': 'b',
+ 'c': 'c',
+ 'd': 'd'
+ }
+
+ def test_invalid_duplicate_key_dict_based_registrar(self):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def dict_based_registrar(*_):
+ return {}
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension1(object):
+ def dict_based_registrar(self):
+ return {
+ 'a': 'val1',
+ }
+
+ @extension_registration
+ class Extension2(object):
+ def dict_based_registrar(self):
+ return {
+ 'a': 'val2',
+ }
+
+ with pytest.raises(RuntimeError):
+ extension_registration.init()
+
+ def test_unsupported_registrar(self):
+ with pytest.raises(RuntimeError):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def unsupported_registrar(*_):
+ return set()
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension(object):
+ def unsupported_registrar(self):
+ return True
+
+ extension_registration.init()
+
+ def test_unimplemented_registration(self):
+ class ExtensionRegistration(extension._ExtensionRegistration):
+ @extension._registrar
+ def list_based_registrar(*_):
+ return []
+ extension_registration = ExtensionRegistration()
+
+ @extension_registration
+ class Extension(object):
+ pass
+
+ assert extension_registration.list_based_registrar() == []
+ extension_registration.init()
+ assert extension_registration.list_based_registrar() == []
[4/4] incubator-ariatosca git commit: Generifying ARIA models
Posted by mx...@apache.org.
Generifying ARIA models
Project: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/commit/6e1f1260
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/tree/6e1f1260
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/diff/6e1f1260
Branch: refs/heads/ARIA-39-Genericize-storage-models
Commit: 6e1f1260f2e1ed10c4f44e2f4dd3dd165e58c9ba
Parents: 5cf84ee
Author: mxmrlv <mx...@gmail.com>
Authored: Mon Dec 12 00:50:09 2016 +0200
Committer: mxmrlv <mx...@gmail.com>
Committed: Tue Dec 20 16:59:50 2016 +0200
----------------------------------------------------------------------
aria/__init__.py | 25 +-
aria/orchestrator/context/workflow.py | 10 +-
aria/orchestrator/workflows/api/task.py | 10 +-
aria/orchestrator/workflows/builtin/heal.py | 11 +-
aria/orchestrator/workflows/core/engine.py | 17 +-
aria/orchestrator/workflows/core/task.py | 23 +-
aria/storage/__init__.py | 12 +-
aria/storage/base_model.py | 677 +++++++++++++++++++
aria/storage/core.py | 2 +-
aria/storage/model.py | 110 +++
aria/storage/models.py | 575 ----------------
aria/storage/structure.py | 180 +++++
aria/storage/structures.py | 244 -------
aria/storage/type.py | 123 ++++
tests/mock/models.py | 49 +-
tests/orchestrator/context/test_toolbelt.py | 8 +-
.../orchestrator/workflows/builtin/test_heal.py | 4 +-
.../orchestrator/workflows/core/test_engine.py | 10 +-
.../workflows/executor/test_executor.py | 7 +-
.../workflows/executor/test_process_executor.py | 6 +-
tests/storage/__init__.py | 7 +-
tests/storage/test_model_storage.py | 64 +-
tests/storage/test_models.py | 195 +++---
23 files changed, 1306 insertions(+), 1063 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/__init__.py
----------------------------------------------------------------------
diff --git a/aria/__init__.py b/aria/__init__.py
index 0f7bec6..a39d58b 100644
--- a/aria/__init__.py
+++ b/aria/__init__.py
@@ -64,22 +64,21 @@ def application_model_storage(api, api_kwargs=None):
Initiate model storage for the supplied storage driver
"""
models = [
- storage.models.Plugin,
- storage.models.ProviderContext,
+ storage.model.Plugin,
- storage.models.Blueprint,
- storage.models.Deployment,
- storage.models.DeploymentUpdate,
- storage.models.DeploymentUpdateStep,
- storage.models.DeploymentModification,
+ storage.model.Blueprint,
+ storage.model.Deployment,
+ storage.model.DeploymentUpdate,
+ storage.model.DeploymentUpdateStep,
+ storage.model.DeploymentModification,
- storage.models.Node,
- storage.models.NodeInstance,
- storage.models.Relationship,
- storage.models.RelationshipInstance,
+ storage.model.Node,
+ storage.model.NodeInstance,
+ storage.model.Relationship,
+ storage.model.RelationshipInstance,
- storage.models.Execution,
- storage.models.Task,
+ storage.model.Execution,
+ storage.model.Task,
]
# if api not in _model_storage:
return storage.ModelStorage(api, items=models, api_kwargs=api_kwargs or {})
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/orchestrator/context/workflow.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/context/workflow.py b/aria/orchestrator/context/workflow.py
index e2e8e25..7f53a9c 100644
--- a/aria/orchestrator/context/workflow.py
+++ b/aria/orchestrator/context/workflow.py
@@ -46,8 +46,7 @@ class WorkflowContext(BaseContext):
execution_cls = self.model.execution.model_cls
now = datetime.utcnow()
execution = self.model.execution.model_cls(
- blueprint_id=self.blueprint.id,
- deployment_id=self.deployment.id,
+ deployment=self.deployment,
workflow_name=self._workflow_name,
created_at=now,
status=execution_cls.PENDING,
@@ -75,9 +74,11 @@ class WorkflowContext(BaseContext):
"""
Iterator over nodes
"""
+ key = 'deployment_{0}'.format(self.model.node_instance.model_cls.name_column_name())
+
return self.model.node.iter(
filters={
- 'deployment_id': self.deployment.id
+ key: getattr(self.deployment, self.deployment.name_column_name())
}
)
@@ -86,9 +87,10 @@ class WorkflowContext(BaseContext):
"""
Iterator over node instances
"""
+ key = 'deployment_{0}'.format(self.model.node_instance.model_cls.name_column_name())
return self.model.node_instance.iter(
filters={
- 'deployment_id': self.deployment.id
+ key: getattr(self.deployment, self.deployment.name_column_name())
}
)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/orchestrator/workflows/api/task.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/api/task.py b/aria/orchestrator/workflows/api/task.py
index 4f025b6..70324a6 100644
--- a/aria/orchestrator/workflows/api/task.py
+++ b/aria/orchestrator/workflows/api/task.py
@@ -18,7 +18,7 @@ Provides the tasks to be entered into the task graph
"""
from uuid import uuid4
-from aria.storage import models
+from aria.storage import model
from ... import context
from .. import exceptions
@@ -75,8 +75,8 @@ class OperationTask(BaseTask):
:param actor: the operation host on which this operation is registered.
:param inputs: operation inputs.
"""
- assert isinstance(actor, (models.NodeInstance,
- models.RelationshipInstance))
+ assert isinstance(actor, (model.NodeInstance,
+ model.RelationshipInstance))
super(OperationTask, self).__init__()
self.actor = actor
self.name = '{name}.{actor.id}'.format(name=name, actor=actor)
@@ -98,7 +98,7 @@ class OperationTask(BaseTask):
:param instance: the node of which this operation belongs to.
:param name: the name of the operation.
"""
- assert isinstance(instance, models.NodeInstance)
+ assert isinstance(instance, model.NodeInstance)
return cls._instance(instance=instance,
name=name,
operation_details=instance.node.operations[name],
@@ -118,7 +118,7 @@ class OperationTask(BaseTask):
with 'source_operations' and 'target_operations'
:param inputs any additional inputs to the operation
"""
- assert isinstance(instance, models.RelationshipInstance)
+ assert isinstance(instance, model.RelationshipInstance)
if operation_end not in [cls.TARGET_OPERATION, cls.SOURCE_OPERATION]:
raise exceptions.TaskException('The operation end should be {0} or {1}'.format(
cls.TARGET_OPERATION, cls.SOURCE_OPERATION
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/orchestrator/workflows/builtin/heal.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/builtin/heal.py b/aria/orchestrator/workflows/builtin/heal.py
index de07095..406a42a 100644
--- a/aria/orchestrator/workflows/builtin/heal.py
+++ b/aria/orchestrator/workflows/builtin/heal.py
@@ -34,7 +34,7 @@ def heal(ctx, graph, node_instance_id):
:return:
"""
failing_node = ctx.model.node_instance.get(node_instance_id)
- host_node = ctx.model.node_instance.get(failing_node.host_id)
+ host_node = ctx.model.node_instance.get(failing_node.host.id)
failed_node_instance_subgraph = _get_contained_subgraph(ctx, host_node)
failed_node_instance_ids = list(n.id for n in failed_node_instance_subgraph)
@@ -163,10 +163,11 @@ def heal_install(ctx, graph, failing_node_instances, targeted_node_instances):
def _get_contained_subgraph(context, host_node_instance):
- contained_instances = [node_instance
- for node_instance in context.node_instances
- if node_instance.host_id == host_node_instance.id and
- node_instance.id != node_instance.host_id]
+ contained_instances = [
+ node_instance
+ for node_instance in context.node_instances
+ if node_instance == host_node_instance and node_instance != node_instance
+ ]
result = [host_node_instance]
if not contained_instances:
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/orchestrator/workflows/core/engine.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/core/engine.py b/aria/orchestrator/workflows/core/engine.py
index 7886b7a..47269a3 100644
--- a/aria/orchestrator/workflows/core/engine.py
+++ b/aria/orchestrator/workflows/core/engine.py
@@ -23,7 +23,7 @@ from datetime import datetime
import networkx
from aria import logger
-from aria.storage import models
+from aria.storage import model
from aria.orchestrator import events
from .. import exceptions
@@ -82,18 +82,18 @@ class Engine(logger.LoggerMixin):
events.on_cancelling_workflow_signal.send(self._workflow_context)
def _is_cancel(self):
- return self._workflow_context.execution.status in [models.Execution.CANCELLING,
- models.Execution.CANCELLED]
+ return self._workflow_context.execution.status in [model.Execution.CANCELLING,
+ model.Execution.CANCELLED]
def _executable_tasks(self):
now = datetime.utcnow()
return (task for task in self._tasks_iter()
- if task.status in models.Task.WAIT_STATES and
+ if task.status in model.Task.WAIT_STATES and
task.due_at <= now and
not self._task_has_dependencies(task))
def _ended_tasks(self):
- return (task for task in self._tasks_iter() if task.status in models.Task.END_STATES)
+ return (task for task in self._tasks_iter() if task.status in model.Task.END_STATES)
def _task_has_dependencies(self, task):
return len(self._execution_graph.pred.get(task.id, {})) > 0
@@ -105,18 +105,19 @@ class Engine(logger.LoggerMixin):
for _, data in self._execution_graph.nodes_iter(data=True):
task = data['task']
if isinstance(task, engine_task.OperationTask):
- self._workflow_context.model.task.refresh(task.model_task)
+ if task.model_task.status not in model.Task.END_STATES:
+ self._workflow_context.model.task.refresh(task.model_task)
yield task
def _handle_executable_task(self, task):
if isinstance(task, engine_task.StubTask):
- task.status = models.Task.SUCCESS
+ task.status = model.Task.SUCCESS
else:
events.sent_task_signal.send(task)
self._executor.execute(task)
def _handle_ended_tasks(self, task):
- if task.status == models.Task.FAILED and not task.ignore_failure:
+ if task.status == model.Task.FAILED and not task.ignore_failure:
raise exceptions.ExecutorException('Workflow failed')
else:
self._execution_graph.remove_node(task.id)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/orchestrator/workflows/core/task.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/core/task.py b/aria/orchestrator/workflows/core/task.py
index 08cf26e..08eebf0 100644
--- a/aria/orchestrator/workflows/core/task.py
+++ b/aria/orchestrator/workflows/core/task.py
@@ -24,7 +24,7 @@ from functools import (
)
from aria import logger
-from aria.storage import models
+from aria.storage import model
from aria.orchestrator.context import operation as operation_context
from .. import exceptions
@@ -66,7 +66,7 @@ class StubTask(BaseTask):
def __init__(self, *args, **kwargs):
super(StubTask, self).__init__(*args, **kwargs)
- self.status = models.Task.PENDING
+ self.status = model.Task.PENDING
self.due_at = datetime.utcnow()
@@ -106,35 +106,36 @@ class OperationTask(BaseTask):
def __init__(self, api_task, *args, **kwargs):
super(OperationTask, self).__init__(id=api_task.id, **kwargs)
self._workflow_context = api_task._workflow_context
- model = api_task._workflow_context.model
+ model_storage = api_task._workflow_context.model
- base_task_model = model.task.model_cls
- if isinstance(api_task.actor, models.NodeInstance):
+ base_task_model = model_storage.task.model_cls
+ if isinstance(api_task.actor, model.NodeInstance):
context_class = operation_context.NodeOperationContext
task_model_cls = base_task_model.as_node_instance
- elif isinstance(api_task.actor, models.RelationshipInstance):
+ elif isinstance(api_task.actor, model.RelationshipInstance):
context_class = operation_context.RelationshipOperationContext
task_model_cls = base_task_model.as_relationship_instance
else:
raise RuntimeError('No operation context could be created for {actor.model_cls}'
.format(actor=api_task.actor))
plugin = api_task.plugin
- plugins = model.plugin.list(filters={'package_name': plugin.get('package_name', ''),
- 'package_version': plugin.get('package_version', '')},
- include=['id'])
+ plugins = model_storage.plugin.list(filters={
+ 'package_name': plugin.get('package_name', ''),
+ 'package_version': plugin.get('package_version', '')
+ }, include=['id'])
# Validation during installation ensures that at most one plugin can exists with provided
# package_name and package_version
plugin_id = plugins[0].id if plugins else None
operation_task = task_model_cls(
name=api_task.name,
operation_mapping=api_task.operation_mapping,
- instance_id=api_task.actor.id,
+ instance_fk=api_task.actor.id,
inputs=api_task.inputs,
status=base_task_model.PENDING,
max_attempts=api_task.max_attempts,
retry_interval=api_task.retry_interval,
ignore_failure=api_task.ignore_failure,
- plugin_id=plugin_id
+ plugin_fk=plugin_id
)
self._workflow_context.model.task.put(operation_task)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/__init__.py
----------------------------------------------------------------------
diff --git a/aria/storage/__init__.py b/aria/storage/__init__.py
index fd69d47..a1c07d7 100644
--- a/aria/storage/__init__.py
+++ b/aria/storage/__init__.py
@@ -45,19 +45,19 @@ from .core import (
from . import (
exceptions,
api,
- structures,
+ structure,
core,
filesystem_rapi,
sql_mapi,
- models
+ model
)
__all__ = (
'exceptions',
- 'structures',
- # 'Storage',
- # 'ModelStorage',
- # 'ResourceStorage',
+ 'structure',
+ 'Storage',
+ 'ModelStorage',
+ 'ResourceStorage',
'filesystem_rapi',
'sql_mapi',
'api'
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/base_model.py
----------------------------------------------------------------------
diff --git a/aria/storage/base_model.py b/aria/storage/base_model.py
new file mode 100644
index 0000000..d5adb4e
--- /dev/null
+++ b/aria/storage/base_model.py
@@ -0,0 +1,677 @@
+# 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's storage.models module
+Path: aria.storage.models
+
+models module holds aria's models.
+
+classes:
+ * Field - represents a single field.
+ * IterField - represents an iterable field.
+ * Model - abstract model implementation.
+ * Snapshot - snapshots implementation model.
+ * Deployment - deployment implementation model.
+ * DeploymentUpdateStep - deployment update step implementation model.
+ * DeploymentUpdate - deployment update implementation model.
+ * DeploymentModification - deployment modification implementation model.
+ * Execution - execution implementation model.
+ * Node - node implementation model.
+ * Relationship - relationship implementation model.
+ * NodeInstance - node instance implementation model.
+ * RelationshipInstance - relationship instance implementation model.
+ * Plugin - plugin implementation model.
+"""
+from collections import namedtuple
+from datetime import datetime
+
+from sqlalchemy.ext.associationproxy import association_proxy
+from sqlalchemy.ext.declarative import declared_attr
+from sqlalchemy import (
+ Column,
+ Integer,
+ Text,
+ DateTime,
+ Boolean,
+ Enum,
+ String,
+ Float,
+ orm,
+)
+
+from .structure import ModelMixin
+
+from .type import (
+ List,
+ Dict
+)
+
+__all__ = (
+ 'BlueprintBase',
+ 'DeploymentBase',
+ 'DeploymentUpdateStepBase',
+ 'DeploymentUpdateBase',
+ 'DeploymentModificationBase',
+ 'ExecutionBase',
+ 'NodeBase',
+ 'RelationshipBase',
+ 'NodeInstanceBase',
+ 'RelationshipInstanceBase',
+ 'PluginBase',
+ 'TaskBase'
+)
+
+#pylint: disable=no-self-argument, abstract-method
+
+
+class BlueprintBase(ModelMixin):
+ """
+ Blueprint model representation.
+ """
+ __tablename__ = 'blueprints'
+
+ created_at = Column(DateTime, nullable=False, index=True)
+ main_file_name = Column(Text, nullable=False)
+ plan = Column(Dict, nullable=False)
+ updated_at = Column(DateTime)
+ description = Column(Text)
+
+
+class DeploymentBase(ModelMixin):
+ """
+ Deployment model representation.
+ """
+ __tablename__ = 'deployments'
+
+ _private_fields = ['blueprint_fk']
+
+ created_at = Column(DateTime, nullable=False, index=True)
+ description = Column(Text)
+ inputs = Column(Dict)
+ groups = Column(Dict)
+ permalink = Column(Text)
+ policy_triggers = Column(Dict)
+ policy_types = Column(Dict)
+ outputs = Column(Dict)
+ scaling_groups = Column(List)
+ updated_at = Column(DateTime)
+ workflows = Column(List)
+
+ @declared_attr
+ def blueprint_fk(cls):
+ return cls.foreign_key(BlueprintBase, nullable=False)
+
+ @declared_attr
+ def blueprint(cls):
+ return cls.one_to_many_relationship('blueprint_fk')
+
+ @declared_attr
+ def blueprint_name(cls):
+ return association_proxy('blueprint', cls.name_column_name())
+
+
+class ExecutionBase(ModelMixin):
+ """
+ Execution model representation.
+ """
+ # Needed only for pylint. the id will be populated by sqlalcehmy and the proper column.
+ __tablename__ = 'executions'
+ _private_fields = ['deployment_fk']
+
+ TERMINATED = 'terminated'
+ FAILED = 'failed'
+ CANCELLED = 'cancelled'
+ PENDING = 'pending'
+ STARTED = 'started'
+ CANCELLING = 'cancelling'
+ FORCE_CANCELLING = 'force_cancelling'
+
+ STATES = [TERMINATED, FAILED, CANCELLED, PENDING, STARTED, CANCELLING, FORCE_CANCELLING]
+ END_STATES = [TERMINATED, FAILED, CANCELLED]
+ ACTIVE_STATES = [state for state in STATES if state not in END_STATES]
+
+ VALID_TRANSITIONS = {
+ PENDING: [STARTED, CANCELLED],
+ STARTED: END_STATES + [CANCELLING],
+ CANCELLING: END_STATES
+ }
+
+ @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 = ExecutionBase.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
+
+ created_at = Column(DateTime, index=True)
+ started_at = Column(DateTime, nullable=True, index=True)
+ ended_at = Column(DateTime, nullable=True, index=True)
+ error = Column(Text, nullable=True)
+ is_system_workflow = Column(Boolean, nullable=False, default=False)
+ parameters = Column(Dict)
+ status = Column(Enum(*STATES, name='execution_status'), default=PENDING)
+ workflow_name = Column(Text)
+
+ @declared_attr
+ def blueprint(cls):
+ return association_proxy('deployment', 'blueprint')
+
+ @declared_attr
+ def deployment_fk(cls):
+ return cls.foreign_key(DeploymentBase, nullable=True)
+
+ @declared_attr
+ def deployment(cls):
+ return cls.one_to_many_relationship('deployment_fk')
+
+ @declared_attr
+ def deployment_name(cls):
+ return association_proxy('deployment', cls.name_column_name())
+
+ @declared_attr
+ def blueprint_name(cls):
+ return association_proxy('deployment', 'blueprint_name')
+
+ def __str__(self):
+ return '<{0} id=`{1}` (status={2})>'.format(
+ self.__class__.__name__,
+ getattr(self, self.name_column_name()),
+ self.status
+ )
+
+
+class DeploymentUpdateBase(ModelMixin):
+ """
+ Deployment update model representation.
+ """
+ # Needed only for pylint. the id will be populated by sqlalcehmy and the proper column.
+ steps = None
+
+ __tablename__ = 'deployment_updates'
+
+ _private_fields = ['execution_fk', 'deployment_fk']
+
+ created_at = Column(DateTime, nullable=False, index=True)
+ deployment_plan = Column(Dict, nullable=False)
+ deployment_update_node_instances = Column(List)
+ deployment_update_deployment = Column(Dict)
+ deployment_update_nodes = Column(List)
+ modified_entity_ids = Column(Dict)
+ state = Column(Text)
+
+ @declared_attr
+ def execution_fk(cls):
+ return cls.foreign_key(ExecutionBase, nullable=True)
+
+ @declared_attr
+ def execution(cls):
+ return cls.one_to_many_relationship('execution_fk')
+
+ @declared_attr
+ def execution_name(cls):
+ return association_proxy('execution', cls.name_column_name())
+
+ @declared_attr
+ def deployment_fk(cls):
+ return cls.foreign_key(DeploymentBase)
+
+ @declared_attr
+ def deployment(cls):
+ return cls.one_to_many_relationship('deployment_fk')
+
+ @declared_attr
+ def deployment_name(cls):
+ return association_proxy('deployment', cls.name_column_name())
+
+ def to_dict(self, suppress_error=False, **kwargs):
+ dep_update_dict = super(DeploymentUpdateBase, 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 DeploymentUpdateStepBase(ModelMixin):
+ """
+ Deployment update step model representation.
+ """
+ # Needed only for pylint. the id will be populated by sqlalcehmy and the proper column.
+ __tablename__ = 'deployment_update_steps'
+ _private_fields = ['deployment_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, '
+ 'POLICY_TYPE, POLICY_TRIGGER, PLUGIN')
+ ENTITY_TYPES = _entity_types(
+ NODE='node',
+ RELATIONSHIP='relationship',
+ PROPERTY='property',
+ OPERATION='operation',
+ WORKFLOW='workflow',
+ OUTPUT='output',
+ DESCRIPTION='description',
+ GROUP='group',
+ POLICY_TYPE='policy_type',
+ POLICY_TRIGGER='policy_trigger',
+ 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)
+
+ @declared_attr
+ def deployment_update_fk(cls):
+ return cls.foreign_key(DeploymentUpdateBase)
+
+ @declared_attr
+ def deployment_update(cls):
+ return cls.one_to_many_relationship('deployment_update_fk', backreference='steps')
+
+ @declared_attr
+ def deployment_update_name(cls):
+ return association_proxy('deployment_update', cls.name_column_name())
+
+ 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 DeploymentModificationBase(ModelMixin):
+ """
+ Deployment modification model representation.
+ """
+ __tablename__ = 'deployment_modifications'
+ _private_fields = ['deployment_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_nodes = Column(Dict)
+ node_instances = Column(Dict)
+ status = Column(Enum(*STATES, name='deployment_modification_status'))
+
+ @declared_attr
+ def deployment_fk(cls):
+ return cls.foreign_key(DeploymentBase)
+
+ @declared_attr
+ def deployment(cls):
+ return cls.one_to_many_relationship('deployment_fk', backreference='modifications')
+
+ @declared_attr
+ def deployment_name(cls):
+ return association_proxy('deployment', cls.name_column_name())
+
+
+class NodeBase(ModelMixin):
+ """
+ Node model representation.
+ """
+ __tablename__ = 'nodes'
+
+ # See base class for an explanation on these properties
+ is_id_unique = False
+
+ _private_fields = ['blueprint_fk', 'host_fk']
+
+ @declared_attr
+ def host_fk(cls):
+ return cls.foreign_key(NodeBase, nullable=True)
+
+ @declared_attr
+ def host(cls):
+ return cls.relationship_to_self('host_fk')
+
+ @declared_attr
+ def host_name(cls):
+ return association_proxy('host', cls.name_column_name())
+
+ @declared_attr
+ def deployment_fk(cls):
+ return cls.foreign_key(DeploymentBase)
+
+ @declared_attr
+ def deployment(cls):
+ return cls.one_to_many_relationship('deployment_fk')
+
+ @declared_attr
+ def deployment_name(cls):
+ return association_proxy('deployment', cls.name_column_name())
+
+ @declared_attr
+ def blueprint_name(cls):
+ return association_proxy('deployment', 'blueprint_{0}'.format(cls.name_column_name()))
+
+ deploy_number_of_instances = Column(Integer, nullable=False)
+ max_number_of_instances = Column(Integer, nullable=False)
+ min_number_of_instances = Column(Integer, nullable=False)
+ number_of_instances = Column(Integer, nullable=False)
+ planned_number_of_instances = Column(Integer, nullable=False)
+ plugins = Column(List)
+ properties = Column(Dict)
+ operations = Column(Dict)
+ type = Column(Text, nullable=False, index=True)
+ type_hierarchy = Column(List)
+
+
+class RelationshipBase(ModelMixin):
+ """
+ Relationship model representation.
+ """
+ __tablename__ = 'relationships'
+
+ _private_fields = ['source_node_fk', 'target_node_fk']
+
+ @declared_attr
+ def source_node_fk(cls):
+ return cls.foreign_key(NodeBase)
+
+ @declared_attr
+ def source_node(cls):
+ return cls.one_to_many_relationship('source_node_fk',
+ backreference='outbound_relationships')
+
+ @declared_attr
+ def source_name(cls):
+ return association_proxy('source_node', cls.name_column_name())
+
+ @declared_attr
+ def target_node_fk(cls):
+ return cls.foreign_key(NodeBase)
+
+ @declared_attr
+ def target_node(cls):
+ return cls.one_to_many_relationship('target_node_fk', backreference='inbound_relationships')
+
+ @declared_attr
+ def target_name(cls):
+ return association_proxy('target_node', cls.name_column_name())
+
+ source_interfaces = Column(Dict)
+ source_operations = Column(Dict, nullable=False)
+ target_interfaces = Column(Dict)
+ target_operations = Column(Dict, nullable=False)
+ type = Column(String, nullable=False)
+ type_hierarchy = Column(List)
+ properties = Column(Dict)
+
+
+class NodeInstanceBase(ModelMixin):
+ """
+ Node instance model representation.
+ """
+ __tablename__ = 'node_instances'
+ _private_fields = ['node_fk', 'host_fk']
+
+ runtime_properties = Column(Dict)
+ scaling_groups = Column(List)
+ state = Column(Text, nullable=False)
+ version = Column(Integer, default=1)
+
+ @declared_attr
+ def host_fk(cls):
+ return cls.foreign_key(NodeInstanceBase, nullable=True)
+
+ @declared_attr
+ def host(cls):
+ return cls.relationship_to_self('host_fk')
+
+ @declared_attr
+ def host_name(cls):
+ return association_proxy('host', cls.name_column_name())
+
+ @declared_attr
+ def deployment(cls):
+ return association_proxy('node', 'deployment')
+
+ @declared_attr
+ def deployment_name(cls):
+ return association_proxy('node', 'deployment_name')
+
+ @declared_attr
+ def node_fk(cls):
+ return cls.foreign_key(NodeBase, nullable=True)
+
+ @declared_attr
+ def node(cls):
+ return cls.one_to_many_relationship('node_fk')
+
+ @declared_attr
+ def node_name(cls):
+ return association_proxy('node', cls.name_column_name())
+
+
+class RelationshipInstanceBase(ModelMixin):
+ """
+ Relationship instance model representation.
+ """
+ __tablename__ = 'relationship_instances'
+ _private_fields = ['relationship_storage_fk',
+ 'source_node_instance_fk',
+ 'target_node_instance_fk']
+
+ @declared_attr
+ def source_node_instance_fk(cls):
+ return cls.foreign_key(NodeInstanceBase)
+
+ @declared_attr
+ def source_node_instance(cls):
+ return cls.one_to_many_relationship('source_node_instance_fk',
+ backreference='outbound_relationship_instances')
+
+ @declared_attr
+ def source_node_instance_name(cls):
+ return association_proxy('source_node_instance', cls.name_column_name())
+
+ @declared_attr
+ def target_node_instance_fk(cls):
+ return cls.foreign_key(NodeInstanceBase)
+
+ @declared_attr
+ def target_node_instance(cls):
+ return cls.one_to_many_relationship('target_node_instance_fk',
+ backreference='inbound_relationship_instances')
+
+ @declared_attr
+ def target_node_instance_name(cls):
+ return association_proxy('target_node_instance', cls.name_column_name())
+
+ @declared_attr
+ def relationship_fk(cls):
+ return cls.foreign_key(RelationshipBase)
+
+ @declared_attr
+ def relationship(cls):
+ return cls.one_to_many_relationship('relationship_fk')
+
+ @declared_attr
+ def relationship_name(cls):
+ return association_proxy('relationship', cls.name_column_name())
+
+
+class PluginBase(ModelMixin):
+ """
+ Plugin model representation.
+ """
+ __tablename__ = 'plugins'
+
+ archive_name = Column(Text, nullable=False, index=True)
+ distribution = Column(Text)
+ distribution_release = Column(Text)
+ distribution_version = Column(Text)
+ package_name = Column(Text, nullable=False, index=True)
+ package_source = Column(Text)
+ package_version = Column(Text)
+ supported_platform = Column(Text)
+ supported_py_versions = Column(List)
+ uploaded_at = Column(DateTime, nullable=False, index=True)
+ wheels = Column(List, nullable=False)
+
+
+class TaskBase(ModelMixin):
+ """
+ A Model which represents an task
+ """
+ __tablename__ = 'tasks'
+ _private_fields = ['node_instance_fk', 'relationship_instance_fk', 'execution_fk']
+
+ @declared_attr
+ def node_instance_fk(cls):
+ return cls.foreign_key(NodeInstanceBase, nullable=True)
+
+ @declared_attr
+ def node_instance_name(cls):
+ return association_proxy('node_instance', cls.name_column_name())
+
+ @declared_attr
+ def node_instance(cls):
+ return cls.one_to_many_relationship('node_instance_fk')
+
+ @declared_attr
+ def relationship_instance_fk(cls):
+ return cls.foreign_key(RelationshipInstanceBase, nullable=True)
+
+ @declared_attr
+ def relationship_instance_name(cls):
+ return association_proxy('relationship_instance', cls.name_column_name())
+
+ @declared_attr
+ def relationship_instance(cls):
+ return cls.one_to_many_relationship('relationship_instance_fk')
+
+ @declared_attr
+ def plugin_fk(cls):
+ return cls.foreign_key(PluginBase, nullable=True)
+
+ @declared_attr
+ def plugin(cls):
+ return cls.one_to_many_relationship('plugin_fk')
+
+ @declared_attr
+ def plugin_name(cls):
+ return association_proxy('plugin', 'name')
+
+ @declared_attr
+ def execution_fk(cls):
+ return cls.foreign_key(ExecutionBase, nullable=True)
+
+ @declared_attr
+ def execution(cls):
+ return cls.one_to_many_relationship('execution_fk')
+
+ @declared_attr
+ def execution_name(cls):
+ return association_proxy('execution', cls.name_column_name())
+
+ PENDING = 'pending'
+ RETRYING = 'retrying'
+ SENT = 'sent'
+ STARTED = 'started'
+ SUCCESS = 'success'
+ FAILED = 'failed'
+ STATES = (
+ PENDING,
+ RETRYING,
+ SENT,
+ STARTED,
+ SUCCESS,
+ FAILED,
+ )
+
+ WAIT_STATES = [PENDING, RETRYING]
+ END_STATES = [SUCCESS, FAILED]
+
+ @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
+
+ INFINITE_RETRIES = -1
+
+ status = Column(Enum(*STATES), name='status', default=PENDING)
+
+ due_at = Column(DateTime, default=datetime.utcnow)
+ started_at = Column(DateTime, default=None)
+ ended_at = Column(DateTime, default=None)
+ max_attempts = Column(Integer, default=1)
+ retry_count = Column(Integer, default=0)
+ retry_interval = Column(Float, default=0)
+ ignore_failure = Column(Boolean, default=False)
+
+ # Operation specific fields
+ operation_mapping = Column(String)
+ inputs = Column(Dict)
+
+ @property
+ def actor(self):
+ """
+ Return the actor of the task
+ :return:
+ ` """
+ return self.node_instance or self.relationship_instance
+
+ @classmethod
+ def as_node_instance(cls, instance_fk, **kwargs):
+ return cls(node_instance_fk=instance_fk, **kwargs)
+
+ @classmethod
+ def as_relationship_instance(cls, instance_fk, **kwargs):
+ return cls(relationship_instance_fk=instance_fk, **kwargs)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/core.py
----------------------------------------------------------------------
diff --git a/aria/storage/core.py b/aria/storage/core.py
index a5d3210..94b4fe0 100644
--- a/aria/storage/core.py
+++ b/aria/storage/core.py
@@ -53,9 +53,9 @@ class Storage(LoggerMixin):
Represents the storage
"""
def __init__(self, api_cls, api_kwargs=None, items=(), **kwargs):
- self._api_kwargs = api_kwargs or {}
super(Storage, self).__init__(**kwargs)
self.api = api_cls
+ self._api_kwargs = api_kwargs or {}
self.registered = {}
for item in items:
self.register(item)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/model.py
----------------------------------------------------------------------
diff --git a/aria/storage/model.py b/aria/storage/model.py
new file mode 100644
index 0000000..afca3e4
--- /dev/null
+++ b/aria/storage/model.py
@@ -0,0 +1,110 @@
+# 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's storage.models module
+Path: aria.storage.models
+
+models module holds aria's models.
+
+classes:
+ * Field - represents a single field.
+ * IterField - represents an iterable field.
+ * Model - abstract model implementation.
+ * Snapshot - snapshots implementation model.
+ * Deployment - deployment implementation model.
+ * DeploymentUpdateStep - deployment update step implementation model.
+ * DeploymentUpdate - deployment update implementation model.
+ * DeploymentModification - deployment modification implementation model.
+ * Execution - execution implementation model.
+ * Node - node implementation model.
+ * Relationship - relationship implementation model.
+ * NodeInstance - node instance implementation model.
+ * RelationshipInstance - relationship instance implementation model.
+ * ProviderContext - provider context implementation model.
+ * Plugin - plugin implementation model.
+"""
+from sqlalchemy.ext.declarative import declarative_base
+
+from . import structure
+from . import base_model as base
+
+__all__ = (
+ 'Blueprint',
+ 'Deployment',
+ 'DeploymentUpdateStep',
+ 'DeploymentUpdate',
+ 'DeploymentModification',
+ 'Execution',
+ 'Node',
+ 'Relationship',
+ 'NodeInstance',
+ 'RelationshipInstance',
+ 'Plugin',
+)
+
+
+#pylint: disable=abstract-method
+# The required abstract method implementation are implemented in the ModelIDMixin, which is used as
+# a base to the DeclerativeBase.
+DeclarativeBase = declarative_base(cls=structure.ModelIDMixin)
+
+
+class Blueprint(DeclarativeBase, base.BlueprintBase):
+ pass
+
+
+class Deployment(DeclarativeBase, base.DeploymentBase):
+ pass
+
+
+class Execution(DeclarativeBase, base.ExecutionBase):
+ pass
+
+
+class DeploymentUpdate(DeclarativeBase, base.DeploymentUpdateBase):
+ pass
+
+
+class DeploymentUpdateStep(DeclarativeBase, base.DeploymentUpdateStepBase):
+ pass
+
+
+class DeploymentModification(DeclarativeBase, base.DeploymentModificationBase):
+ pass
+
+
+class Node(DeclarativeBase, base.NodeBase):
+ pass
+
+
+class Relationship(DeclarativeBase, base.RelationshipBase):
+ pass
+
+
+class NodeInstance(DeclarativeBase, base.NodeInstanceBase):
+ pass
+
+
+class RelationshipInstance(DeclarativeBase, base.RelationshipInstanceBase):
+ pass
+
+
+class Plugin(DeclarativeBase, base.PluginBase):
+ pass
+
+
+class Task(DeclarativeBase, base.TaskBase):
+ pass
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/models.py
----------------------------------------------------------------------
diff --git a/aria/storage/models.py b/aria/storage/models.py
deleted file mode 100644
index 0a1027b..0000000
--- a/aria/storage/models.py
+++ /dev/null
@@ -1,575 +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's storage.models module
-Path: aria.storage.models
-
-models module holds aria's models.
-
-classes:
- * Field - represents a single field.
- * IterField - represents an iterable field.
- * Model - abstract model implementation.
- * Snapshot - snapshots implementation model.
- * Deployment - deployment implementation model.
- * DeploymentUpdateStep - deployment update step implementation model.
- * DeploymentUpdate - deployment update implementation model.
- * DeploymentModification - deployment modification implementation model.
- * Execution - execution implementation model.
- * Node - node implementation model.
- * Relationship - relationship implementation model.
- * NodeInstance - node instance implementation model.
- * RelationshipInstance - relationship instance implementation model.
- * ProviderContext - provider context implementation model.
- * Plugin - plugin implementation model.
-"""
-from collections import namedtuple
-from datetime import datetime
-
-from sqlalchemy.ext.declarative.base import declared_attr
-
-from .structures import (
- SQLModelBase,
- Column,
- Integer,
- Text,
- DateTime,
- Boolean,
- Enum,
- String,
- Float,
- List,
- Dict,
- foreign_key,
- one_to_many_relationship,
- relationship_to_self,
- orm)
-
-__all__ = (
- 'Blueprint',
- 'Deployment',
- 'DeploymentUpdateStep',
- 'DeploymentUpdate',
- 'DeploymentModification',
- 'Execution',
- 'Node',
- 'Relationship',
- 'NodeInstance',
- 'RelationshipInstance',
- 'ProviderContext',
- 'Plugin',
-)
-
-
-#pylint: disable=no-self-argument
-
-
-class Blueprint(SQLModelBase):
- """
- Blueprint model representation.
- """
- __tablename__ = 'blueprints'
-
- name = Column(Text, index=True)
- created_at = Column(DateTime, nullable=False, index=True)
- main_file_name = Column(Text, nullable=False)
- plan = Column(Dict, nullable=False)
- updated_at = Column(DateTime)
- description = Column(Text)
-
-
-class Deployment(SQLModelBase):
- """
- Deployment model representation.
- """
- __tablename__ = 'deployments'
-
- _private_fields = ['blueprint_id']
-
- blueprint_id = foreign_key(Blueprint.id)
-
- name = Column(Text, index=True)
- created_at = Column(DateTime, nullable=False, index=True)
- description = Column(Text)
- inputs = Column(Dict)
- groups = Column(Dict)
- permalink = Column(Text)
- policy_triggers = Column(Dict)
- policy_types = Column(Dict)
- outputs = Column(Dict)
- scaling_groups = Column(Dict)
- updated_at = Column(DateTime)
- workflows = Column(Dict)
-
- @declared_attr
- def blueprint(cls):
- return one_to_many_relationship(cls, Blueprint, cls.blueprint_id)
-
-
-class Execution(SQLModelBase):
- """
- Execution model representation.
- """
- __tablename__ = 'executions'
-
- TERMINATED = 'terminated'
- FAILED = 'failed'
- CANCELLED = 'cancelled'
- PENDING = 'pending'
- STARTED = 'started'
- CANCELLING = 'cancelling'
- FORCE_CANCELLING = 'force_cancelling'
-
- STATES = [TERMINATED, FAILED, CANCELLED, PENDING, STARTED, CANCELLING, FORCE_CANCELLING]
- END_STATES = [TERMINATED, FAILED, CANCELLED]
- ACTIVE_STATES = [state for state in STATES if state not in END_STATES]
-
- VALID_TRANSITIONS = {
- PENDING: [STARTED, CANCELLED],
- STARTED: END_STATES + [CANCELLING],
- CANCELLING: END_STATES
- }
-
- @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 = Execution.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
-
- deployment_id = foreign_key(Deployment.id)
- blueprint_id = foreign_key(Blueprint.id)
- _private_fields = ['deployment_id', 'blueprint_id']
-
- created_at = Column(DateTime, index=True)
- started_at = Column(DateTime, nullable=True, index=True)
- ended_at = Column(DateTime, nullable=True, index=True)
- error = Column(Text, nullable=True)
- is_system_workflow = Column(Boolean, nullable=False, default=False)
- parameters = Column(Dict)
- status = Column(Enum(*STATES, name='execution_status'), default=PENDING)
- workflow_name = Column(Text, nullable=False)
-
- @declared_attr
- def deployment(cls):
- return one_to_many_relationship(cls, Deployment, cls.deployment_id)
-
- @declared_attr
- def blueprint(cls):
- return one_to_many_relationship(cls, Blueprint, cls.blueprint_id)
-
- def __str__(self):
- return '<{0} id=`{1}` (status={2})>'.format(
- self.__class__.__name__,
- self.id,
- self.status
- )
-
-
-class DeploymentUpdate(SQLModelBase):
- """
- Deployment update model representation.
- """
- __tablename__ = 'deployment_updates'
-
- deployment_id = foreign_key(Deployment.id)
- execution_id = foreign_key(Execution.id, nullable=True)
- _private_fields = ['execution_id', 'deployment_id']
-
- created_at = Column(DateTime, nullable=False, index=True)
- deployment_plan = Column(Dict, nullable=False)
- deployment_update_node_instances = Column(Dict)
- deployment_update_deployment = Column(Dict)
- deployment_update_nodes = Column(Dict)
- modified_entity_ids = Column(Dict)
- state = Column(Text)
-
- @declared_attr
- def execution(cls):
- return one_to_many_relationship(cls, Execution, cls.execution_id)
-
- @declared_attr
- def deployment(cls):
- return one_to_many_relationship(cls, Deployment, cls.deployment_id)
-
- def to_dict(self, suppress_error=False, **kwargs):
- dep_update_dict = super(DeploymentUpdate, self).to_dict(suppress_error)
- # Taking care of the fact the DeploymentSteps are objects
- dep_update_dict['steps'] = [step.to_dict() for step in self.steps]
- return dep_update_dict
-
-
-class DeploymentUpdateStep(SQLModelBase):
- """
- Deployment update step model representation.
- """
- __tablename__ = 'deployment_update_steps'
- _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, '
- 'POLICY_TYPE, POLICY_TRIGGER, PLUGIN')
- ENTITY_TYPES = _entity_types(
- NODE='node',
- RELATIONSHIP='relationship',
- PROPERTY='property',
- OPERATION='operation',
- WORKFLOW='workflow',
- OUTPUT='output',
- DESCRIPTION='description',
- GROUP='group',
- POLICY_TYPE='policy_type',
- POLICY_TRIGGER='policy_trigger',
- PLUGIN='plugin'
- )
-
- deployment_update_id = foreign_key(DeploymentUpdate.id)
- _private_fields = ['deployment_update_id']
-
- 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)
-
- @declared_attr
- def deployment_update(cls):
- return one_to_many_relationship(cls,
- DeploymentUpdate,
- cls.deployment_update_id,
- backreference='steps')
-
- def __hash__(self):
- return hash((self.id, 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 DeploymentModification(SQLModelBase):
- """
- Deployment modification model representation.
- """
- __tablename__ = 'deployment_modifications'
-
- STARTED = 'started'
- FINISHED = 'finished'
- ROLLEDBACK = 'rolledback'
-
- STATES = [STARTED, FINISHED, ROLLEDBACK]
- END_STATES = [FINISHED, ROLLEDBACK]
-
- deployment_id = foreign_key(Deployment.id)
- _private_fields = ['deployment_id']
-
- context = Column(Dict)
- created_at = Column(DateTime, nullable=False, index=True)
- ended_at = Column(DateTime, index=True)
- modified_nodes = Column(Dict)
- node_instances = Column(Dict)
- status = Column(Enum(*STATES, name='deployment_modification_status'))
-
- @declared_attr
- def deployment(cls):
- return one_to_many_relationship(cls,
- Deployment,
- cls.deployment_id,
- backreference='modifications')
-
-
-class Node(SQLModelBase):
- """
- Node model representation.
- """
- __tablename__ = 'nodes'
-
- # See base class for an explanation on these properties
- is_id_unique = False
-
- name = Column(Text, index=True)
- _private_fields = ['deployment_id', 'host_id']
- deployment_id = foreign_key(Deployment.id)
- host_id = foreign_key('nodes.id', nullable=True)
-
- @declared_attr
- def deployment(cls):
- return one_to_many_relationship(cls, Deployment, cls.deployment_id)
-
- deploy_number_of_instances = Column(Integer, nullable=False)
- # TODO: This probably should be a foreign key, but there's no guarantee
- # in the code, currently, that the host will be created beforehand
- max_number_of_instances = Column(Integer, nullable=False)
- min_number_of_instances = Column(Integer, nullable=False)
- number_of_instances = Column(Integer, nullable=False)
- planned_number_of_instances = Column(Integer, nullable=False)
- plugins = Column(List)
- properties = Column(Dict)
- operations = Column(Dict)
- type = Column(Text, nullable=False, index=True)
- type_hierarchy = Column(List)
-
- @declared_attr
- def host(cls):
- return relationship_to_self(cls, cls.host_id, cls.id)
-
-
-class Relationship(SQLModelBase):
- """
- Relationship model representation.
- """
- __tablename__ = 'relationships'
-
- _private_fields = ['source_node_id', 'target_node_id']
-
- source_node_id = foreign_key(Node.id)
- target_node_id = foreign_key(Node.id)
-
- @declared_attr
- def source_node(cls):
- return one_to_many_relationship(cls,
- Node,
- cls.source_node_id,
- 'outbound_relationships')
-
- @declared_attr
- def target_node(cls):
- return one_to_many_relationship(cls,
- Node,
- cls.target_node_id,
- 'inbound_relationships')
-
- source_interfaces = Column(Dict)
- source_operations = Column(Dict, nullable=False)
- target_interfaces = Column(Dict)
- target_operations = Column(Dict, nullable=False)
- type = Column(String, nullable=False)
- type_hierarchy = Column(List)
- properties = Column(Dict)
-
-
-class NodeInstance(SQLModelBase):
- """
- Node instance model representation.
- """
- __tablename__ = 'node_instances'
-
- node_id = foreign_key(Node.id)
- deployment_id = foreign_key(Deployment.id)
- host_id = foreign_key('node_instances.id', nullable=True)
-
- _private_fields = ['node_id', 'host_id']
-
- name = Column(Text, index=True)
- runtime_properties = Column(Dict)
- scaling_groups = Column(Dict)
- state = Column(Text, nullable=False)
- version = Column(Integer, default=1)
-
- @declared_attr
- def deployment(cls):
- return one_to_many_relationship(cls, Deployment, cls.deployment_id)
-
- @declared_attr
- def node(cls):
- return one_to_many_relationship(cls, Node, cls.node_id)
-
- @declared_attr
- def host(cls):
- return relationship_to_self(cls, cls.host_id, cls.id)
-
-
-class RelationshipInstance(SQLModelBase):
- """
- Relationship instance model representation.
- """
- __tablename__ = 'relationship_instances'
-
- relationship_id = foreign_key(Relationship.id)
- source_node_instance_id = foreign_key(NodeInstance.id)
- target_node_instance_id = foreign_key(NodeInstance.id)
-
- _private_fields = ['relationship_storage_id',
- 'source_node_instance_id',
- 'target_node_instance_id']
-
- @declared_attr
- def source_node_instance(cls):
- return one_to_many_relationship(cls,
- NodeInstance,
- cls.source_node_instance_id,
- 'outbound_relationship_instances')
-
- @declared_attr
- def target_node_instance(cls):
- return one_to_many_relationship(cls,
- NodeInstance,
- cls.target_node_instance_id,
- 'inbound_relationship_instances')
-
- @declared_attr
- def relationship(cls):
- return one_to_many_relationship(cls, Relationship, cls.relationship_id)
-
-
-class ProviderContext(SQLModelBase):
- """
- Provider context model representation.
- """
- __tablename__ = 'provider_context'
-
- name = Column(Text, nullable=False)
- context = Column(Dict, nullable=False)
-
-
-class Plugin(SQLModelBase):
- """
- Plugin model representation.
- """
- __tablename__ = 'plugins'
-
- archive_name = Column(Text, nullable=False, index=True)
- distribution = Column(Text)
- distribution_release = Column(Text)
- distribution_version = Column(Text)
- package_name = Column(Text, nullable=False, index=True)
- package_source = Column(Text)
- package_version = Column(Text)
- supported_platform = Column(Text)
- supported_py_versions = Column(List)
- uploaded_at = Column(DateTime, nullable=False, index=True)
- wheels = Column(List, nullable=False)
-
-
-class Task(SQLModelBase):
- """
- A Model which represents an task
- """
-
- __tablename__ = 'task'
- node_instance_id = foreign_key(NodeInstance.id, nullable=True)
- relationship_instance_id = foreign_key(RelationshipInstance.id, nullable=True)
- execution_id = foreign_key(Execution.id, nullable=True)
-
- _private_fields = ['node_instance_id',
- 'relationship_instance_id',
- 'execution_id']
-
- @declared_attr
- def node_instance(cls):
- return one_to_many_relationship(cls, NodeInstance, cls.node_instance_id)
-
- @declared_attr
- def relationship_instance(cls):
- return one_to_many_relationship(cls,
- RelationshipInstance,
- cls.relationship_instance_id)
-
- PENDING = 'pending'
- RETRYING = 'retrying'
- SENT = 'sent'
- STARTED = 'started'
- SUCCESS = 'success'
- FAILED = 'failed'
- STATES = (
- PENDING,
- RETRYING,
- SENT,
- STARTED,
- SUCCESS,
- FAILED,
- )
-
- WAIT_STATES = [PENDING, RETRYING]
- END_STATES = [SUCCESS, FAILED]
-
- @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 != Task.INFINITE_RETRIES:
- raise ValueError('Max attempts can be either -1 (infinite) or any positive number. '
- 'Got {value}'.format(value=value))
- return value
-
- INFINITE_RETRIES = -1
-
- status = Column(Enum(*STATES), name='status', default=PENDING)
-
- due_at = Column(DateTime, default=datetime.utcnow)
- started_at = Column(DateTime, default=None)
- ended_at = Column(DateTime, default=None)
- max_attempts = Column(Integer, default=1)
- retry_count = Column(Integer, default=0)
- retry_interval = Column(Float, default=0)
- ignore_failure = Column(Boolean, default=False)
-
- # Operation specific fields
- name = Column(String)
- operation_mapping = Column(String)
- inputs = Column(Dict)
- plugin_id = foreign_key(Plugin.id, nullable=True)
-
- @declared_attr
- def plugin(cls):
- return one_to_many_relationship(cls, Plugin, cls.plugin_id)
-
- @declared_attr
- def execution(cls):
- return one_to_many_relationship(cls, Execution, cls.execution_id)
-
- @property
- def actor(self):
- """
- Return the actor of the task
- :return:
- """
- return self.node_instance or self.relationship_instance
-
- @classmethod
- def as_node_instance(cls, instance_id, **kwargs):
- return cls(node_instance_id=instance_id, **kwargs)
-
- @classmethod
- def as_relationship_instance(cls, instance_id, **kwargs):
- return cls(relationship_instance_id=instance_id, **kwargs)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/structure.py
----------------------------------------------------------------------
diff --git a/aria/storage/structure.py b/aria/storage/structure.py
new file mode 100644
index 0000000..fe6a144
--- /dev/null
+++ b/aria/storage/structure.py
@@ -0,0 +1,180 @@
+# 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's storage.structures module
+Path: aria.storage.structures
+
+models module holds aria's models.
+
+classes:
+ * Field - represents a single field.
+ * IterField - represents an iterable field.
+ * PointerField - represents a single pointer field.
+ * IterPointerField - represents an iterable pointers field.
+ * Model - abstract model implementation.
+"""
+
+from sqlalchemy.orm import relationship, backref
+from sqlalchemy.ext import associationproxy
+from sqlalchemy import (
+ Column,
+ ForeignKey,
+ Integer,
+ Text
+)
+
+
+class ModelMixin(object):
+
+ @classmethod
+ def id_column_name(cls):
+ raise NotImplementedError
+
+ @classmethod
+ def name_column_name(cls):
+ raise NotImplementedError
+
+ @classmethod
+ def _get_cls_by_tablename(cls, tablename):
+ """Return class reference mapped to table.
+
+ :param tablename: String with name of table.
+ :return: Class reference or None.
+ """
+ if tablename in (cls.__name__, cls.__tablename__):
+ return cls
+
+ for table_cls in cls._decl_class_registry.values():
+ if tablename in (getattr(table_cls, '__name__', None),
+ getattr(table_cls, '__tablename__', None)):
+ return table_cls
+
+ @classmethod
+ def foreign_key(cls, table, nullable=False):
+ """Return a ForeignKey object with the relevant
+
+ :param table: Unique id column in the parent table
+ :param nullable: Should the column be allowed to remain empty
+ """
+ table = cls._get_cls_by_tablename(table.__tablename__)
+ foreign_key_str = '{tablename}.{unique_id}'.format(tablename=table.__tablename__,
+ unique_id=table.id_column_name())
+ column = Column(ForeignKey(foreign_key_str, ondelete='CASCADE'),
+ nullable=nullable)
+ column.__remote_table_name = table.__name__
+ return column
+
+ @classmethod
+ def one_to_many_relationship(cls,
+ foreign_key_column,
+ backreference=None):
+ """Return a one-to-many SQL relationship object
+ Meant to be used from inside the *child* object
+
+ :param parent_class: Class of the parent table
+ :param cls: Class of the child table
+ :param foreign_key_column: The column of the foreign key (from the child table)
+ :param backreference: The name to give to the reference to the child (on the parent table)
+ """
+ parent_table = cls._get_cls_by_tablename(
+ getattr(cls, foreign_key_column).__remote_table_name)
+ primaryjoin_str = '{parent_class_name}.{parent_unique_id} == ' \
+ '{child_class.__name__}.{foreign_key_column}'\
+ .format(
+ parent_class_name=parent_table.__name__,
+ parent_unique_id=parent_table.id_column_name(),
+ child_class=cls,
+ foreign_key_column=foreign_key_column
+ )
+ return relationship(
+ parent_table.__name__,
+ primaryjoin=primaryjoin_str,
+ foreign_keys=[getattr(cls, foreign_key_column)],
+ # The following line make sure that when the *parent* is
+ # deleted, all its connected children are deleted as well
+ backref=backref(backreference or cls.__tablename__, cascade='all'),
+ )
+
+ @classmethod
+ def relationship_to_self(cls, local_column):
+
+ remote_side_str = '{cls.__name__}.{remote_column}'.format(
+ cls=cls,
+ remote_column=cls.id_column_name()
+ )
+ primaryjoin_str = '{remote_side_str} == {cls.__name__}.{local_column}'.format(
+ remote_side_str=remote_side_str,
+ cls=cls,
+ local_column=local_column)
+ return relationship(cls.__name__,
+ primaryjoin=primaryjoin_str,
+ remote_side=remote_side_str,
+ post_update=True)
+
+ def to_dict(self, suppress_error=False):
+ """Return a dict representation of the model
+
+ :param suppress_error: If set to True, sets `None` to attributes that
+ it's unable to retrieve (e.g., if a relationship wasn't established
+ yet, and so it's impossible to access a property through it)
+ """
+ if suppress_error:
+ res = dict()
+ for field in self.get_fields():
+ try:
+ field_value = getattr(self, field)
+ except AttributeError:
+ field_value = None
+ res[field] = field_value
+ else:
+ # Can't simply call here `self.to_response()` because inheriting
+ # class might override it, but we always need the same code here
+ res = dict((f, getattr(self, f)) for f in self.fields())
+ return res
+
+ @classmethod
+ def _association_proxies(cls):
+ for col, value in cls.__table__.columns.items():
+ if isinstance(value, associationproxy.AssociationProxy):
+ yield col
+
+ @classmethod
+ def fields(cls):
+ """Return the list of field names for this table
+
+ Mostly for backwards compatibility in the code (that uses `fields`)
+ """
+ fields = set(cls._association_proxies())
+ fields.update(cls.__table__.columns.keys())
+ return fields - set(cls._private_fields)
+
+ def __repr__(self):
+ return '<{__class__.__name__} id=`{id}`>'.format(
+ __class__=self.__class__,
+ id=getattr(self, self.name_column_name()))
+
+
+class ModelIDMixin(object):
+ id = Column(Integer, primary_key=True, autoincrement=True)
+ name = Column(Text, nullable=True, index=True)
+
+ @classmethod
+ def id_column_name(cls):
+ return 'id'
+
+ @classmethod
+ def name_column_name(cls):
+ return 'name'
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/structures.py
----------------------------------------------------------------------
diff --git a/aria/storage/structures.py b/aria/storage/structures.py
deleted file mode 100644
index 8afa40c..0000000
--- a/aria/storage/structures.py
+++ /dev/null
@@ -1,244 +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's storage.structures module
-Path: aria.storage.structures
-
-models module holds aria's models.
-
-classes:
- * Field - represents a single field.
- * IterField - represents an iterable field.
- * PointerField - represents a single pointer field.
- * IterPointerField - represents an iterable pointers field.
- * Model - abstract model implementation.
-"""
-import json
-
-from sqlalchemy.ext.mutable import Mutable
-from sqlalchemy.orm import relationship, backref
-from sqlalchemy.ext.declarative import declarative_base
-# pylint: disable=unused-import
-from sqlalchemy.ext.associationproxy import association_proxy
-from sqlalchemy import (
- schema,
- VARCHAR,
- ARRAY,
- Column,
- Integer,
- Text,
- DateTime,
- Boolean,
- Enum,
- String,
- PickleType,
- Float,
- TypeDecorator,
- ForeignKey,
- orm,
-)
-
-from aria.storage import exceptions
-
-Model = declarative_base()
-
-
-def foreign_key(foreign_key_column, nullable=False):
- """Return a ForeignKey object with the relevant
-
- :param foreign_key_column: Unique id column in the parent table
- :param nullable: Should the column be allowed to remain empty
- """
- return Column(
- ForeignKey(foreign_key_column, ondelete='CASCADE'),
- nullable=nullable
- )
-
-
-def one_to_many_relationship(child_class,
- parent_class,
- foreign_key_column,
- backreference=None):
- """Return a one-to-many SQL relationship object
- Meant to be used from inside the *child* object
-
- :param parent_class: Class of the parent table
- :param child_class: Class of the child table
- :param foreign_key_column: The column of the foreign key
- :param backreference: The name to give to the reference to the child
- """
- backreference = backreference or child_class.__tablename__
- return relationship(
- parent_class,
- primaryjoin=lambda: parent_class.id == foreign_key_column,
- # The following line make sure that when the *parent* is
- # deleted, all its connected children are deleted as well
- backref=backref(backreference, cascade='all')
- )
-
-
-def relationship_to_self(self_cls, parent_key, self_key):
- return relationship(
- self_cls,
- foreign_keys=parent_key,
- remote_side=self_key
- )
-
-
-class _MutableType(TypeDecorator):
- """
- Dict representation of type.
- """
- @property
- def python_type(self):
- raise NotImplementedError
-
- impl = VARCHAR
-
- def process_literal_param(self, value, dialect):
- pass
-
- def process_bind_param(self, value, dialect):
- if value is not None:
- value = json.dumps(value)
- return value
-
- def process_result_value(self, value, dialect):
- if value is not None:
- value = json.loads(value)
- return value
-
-
-class _DictType(_MutableType):
- @property
- def python_type(self):
- return dict
-
-
-class _ListType(_MutableType):
- @property
- def python_type(self):
- return list
-
-
-class _MutableDict(Mutable, dict):
- """
- Enables tracking for dict values.
- """
- @classmethod
- def coerce(cls, key, value):
- "Convert plain dictionaries to MutableDict."
-
- if not isinstance(value, _MutableDict):
- if isinstance(value, dict):
- return _MutableDict(value)
-
- # this call will raise ValueError
- try:
- return Mutable.coerce(key, value)
- except ValueError as e:
- raise exceptions.StorageError('SQL Storage error: {0}'.format(str(e)))
- else:
- return value
-
- def __setitem__(self, key, value):
- "Detect dictionary set events and emit change events."
-
- dict.__setitem__(self, key, value)
- self.changed()
-
- def __delitem__(self, key):
- "Detect dictionary del events and emit change events."
-
- dict.__delitem__(self, key)
- self.changed()
-
-
-class _MutableList(Mutable, list):
-
- @classmethod
- def coerce(cls, key, value):
- "Convert plain dictionaries to MutableDict."
-
- if not isinstance(value, _MutableList):
- if isinstance(value, list):
- return _MutableList(value)
-
- # this call will raise ValueError
- try:
- return Mutable.coerce(key, value)
- except ValueError as e:
- raise exceptions.StorageError('SQL Storage error: {0}'.format(str(e)))
- else:
- return value
-
- def __setitem__(self, key, value):
- list.__setitem__(self, key, value)
- self.changed()
-
- def __delitem__(self, key):
- list.__delitem__(self, key)
-
-
-Dict = _MutableDict.as_mutable(_DictType)
-List = _MutableList.as_mutable(_ListType)
-
-
-class SQLModelBase(Model):
- """
- Abstract base class for all SQL models that allows [de]serialization
- """
- # SQLAlchemy syntax
- __abstract__ = True
-
- # This would be overridden once the models are created. Created for pylint.
- __table__ = None
-
- _private_fields = []
-
- id = Column(Integer, primary_key=True, autoincrement=True)
-
- def to_dict(self, suppress_error=False):
- """Return a dict representation of the model
-
- :param suppress_error: If set to True, sets `None` to attributes that
- it's unable to retrieve (e.g., if a relationship wasn't established
- yet, and so it's impossible to access a property through it)
- """
- if suppress_error:
- res = dict()
- for field in self.fields():
- try:
- field_value = getattr(self, field)
- except AttributeError:
- field_value = None
- res[field] = field_value
- else:
- # Can't simply call here `self.to_response()` because inheriting
- # class might override it, but we always need the same code here
- res = dict((f, getattr(self, f)) for f in self.fields())
- return res
-
- @classmethod
- def fields(cls):
- """Return the list of field names for this table
-
- Mostly for backwards compatibility in the code (that uses `fields`)
- """
- return set(cls.__table__.columns.keys()) - set(cls._private_fields)
-
- def __repr__(self):
- return '<{0} id=`{1}`>'.format(self.__class__.__name__, self.id)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/aria/storage/type.py
----------------------------------------------------------------------
diff --git a/aria/storage/type.py b/aria/storage/type.py
new file mode 100644
index 0000000..b168b7f
--- /dev/null
+++ b/aria/storage/type.py
@@ -0,0 +1,123 @@
+# 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.
+import json
+
+from sqlalchemy import (
+ TypeDecorator,
+ VARCHAR
+)
+
+from sqlalchemy.ext import mutable
+
+from . import exceptions
+
+
+class _MutableType(TypeDecorator):
+ """
+ Dict representation of type.
+ """
+ @property
+ def python_type(self):
+ raise NotImplementedError
+
+ def process_literal_param(self, value, dialect):
+ pass
+
+ impl = VARCHAR
+
+ def process_bind_param(self, value, dialect):
+ if value is not None:
+ value = json.dumps(value)
+ return value
+
+ def process_result_value(self, value, dialect):
+ if value is not None:
+ value = json.loads(value)
+ return value
+
+
+class Dict(_MutableType):
+ @property
+ def python_type(self):
+ return dict
+
+
+class List(_MutableType):
+ @property
+ def python_type(self):
+ return list
+
+
+class _MutableDict(mutable.Mutable, dict):
+ """
+ Enables tracking for dict values.
+ """
+ @classmethod
+ def coerce(cls, key, value):
+ "Convert plain dictionaries to MutableDict."
+
+ if not isinstance(value, _MutableDict):
+ if isinstance(value, dict):
+ return _MutableDict(value)
+
+ # this call will raise ValueError
+ try:
+ return mutable.Mutable.coerce(key, value)
+ except ValueError as e:
+ raise exceptions.StorageError('SQL Storage error: {0}'.format(str(e)))
+ else:
+ return value
+
+ def __setitem__(self, key, value):
+ "Detect dictionary set events and emit change events."
+
+ dict.__setitem__(self, key, value)
+ self.changed()
+
+ def __delitem__(self, key):
+ "Detect dictionary del events and emit change events."
+
+ dict.__delitem__(self, key)
+ self.changed()
+
+
+class _MutableList(mutable.Mutable, list):
+
+ @classmethod
+ def coerce(cls, key, value):
+ "Convert plain dictionaries to MutableDict."
+
+ if not isinstance(value, _MutableList):
+ if isinstance(value, list):
+ return _MutableList(value)
+
+ # this call will raise ValueError
+ try:
+ return mutable.Mutable.coerce(key, value)
+ except ValueError as e:
+ raise exceptions.StorageError('SQL Storage error: {0}'.format(str(e)))
+ else:
+ return value
+
+ def __setitem__(self, key, value):
+ list.__setitem__(self, key, value)
+ self.changed()
+
+ def __delitem__(self, key):
+ list.__delitem__(self, key)
+
+
+_MutableDict.associate_with(Dict)
+_MutableList.as_mutable(List)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/mock/models.py
----------------------------------------------------------------------
diff --git a/tests/mock/models.py b/tests/mock/models.py
index 26088e0..433bf4c 100644
--- a/tests/mock/models.py
+++ b/tests/mock/models.py
@@ -15,7 +15,7 @@
from datetime import datetime
-from aria.storage import models
+from aria.storage import model
from . import operations
@@ -35,7 +35,7 @@ RELATIONSHIP_INSTANCE_NAME = 'relationship_instance'
def get_dependency_node(deployment):
- return models.Node(
+ return model.Node(
name=DEPENDENCY_NODE_NAME,
type='test_node_type',
type_hierarchy=[],
@@ -46,26 +46,25 @@ def get_dependency_node(deployment):
operations=dict((key, {}) for key in operations.NODE_OPERATIONS),
min_number_of_instances=1,
max_number_of_instances=1,
- deployment_id=deployment.id
+ deployment_fk=deployment.id
)
def get_dependency_node_instance(dependency_node):
- return models.NodeInstance(
+ return model.NodeInstance(
name=DEPENDENCY_NODE_INSTANCE_NAME,
runtime_properties={'ip': '1.1.1.1'},
version=None,
- node_id=dependency_node.id,
- deployment_id=dependency_node.deployment.id,
+ node_fk=dependency_node.id,
state='',
scaling_groups={}
)
def get_relationship(source=None, target=None):
- return models.Relationship(
- source_node_id=source.id,
- target_node_id=target.id,
+ return model.Relationship(
+ source_node_fk=source.id,
+ target_node_fk=target.id,
source_interfaces={},
source_operations=dict((key, {}) for key in operations.RELATIONSHIP_OPERATIONS),
target_interfaces={},
@@ -77,17 +76,17 @@ def get_relationship(source=None, target=None):
def get_relationship_instance(source_instance, target_instance, relationship):
- return models.RelationshipInstance(
- relationship_id=relationship.id,
- target_node_instance_id=target_instance.id,
- source_node_instance_id=source_instance.id,
+ return model.RelationshipInstance(
+ relationship_fk=relationship.id,
+ target_node_instance_fk=target_instance.id,
+ source_node_instance_fk=source_instance.id,
)
def get_dependent_node(deployment):
- return models.Node(
+ return model.Node(
name=DEPENDENT_NODE_NAME,
- deployment_id=deployment.id,
+ deployment_fk=deployment.id,
type='test_node_type',
type_hierarchy=[],
number_of_instances=1,
@@ -101,12 +100,11 @@ def get_dependent_node(deployment):
def get_dependent_node_instance(dependent_node):
- return models.NodeInstance(
+ return model.NodeInstance(
name=DEPENDENT_NODE_INSTANCE_NAME,
runtime_properties={},
version=None,
- node_id=dependent_node.id,
- deployment_id=dependent_node.deployment.id,
+ node_fk=dependent_node.id,
state='',
scaling_groups={}
)
@@ -114,7 +112,7 @@ def get_dependent_node_instance(dependent_node):
def get_blueprint():
now = datetime.now()
- return models.Blueprint(
+ return model.Blueprint(
plan={},
name=BLUEPRINT_NAME,
description=None,
@@ -125,10 +123,9 @@ def get_blueprint():
def get_execution(deployment):
- return models.Execution(
- deployment_id=deployment.id,
- blueprint_id=deployment.blueprint.id,
- status=models.Execution.STARTED,
+ return model.Execution(
+ deployment_fk=deployment.id,
+ status=model.Execution.STARTED,
workflow_name=WORKFLOW_NAME,
started_at=datetime.utcnow(),
parameters=None
@@ -137,9 +134,9 @@ def get_execution(deployment):
def get_deployment(blueprint):
now = datetime.utcnow()
- return models.Deployment(
+ return model.Deployment(
name=DEPLOYMENT_NAME,
- blueprint_id=blueprint.id,
+ blueprint_fk=blueprint.id,
description='',
created_at=now,
updated_at=now,
@@ -155,7 +152,7 @@ def get_deployment(blueprint):
def get_plugin(package_name='package', package_version='0.1'):
- return models.Plugin(
+ return model.Plugin(
archive_name='archive_name',
distribution='distribution',
distribution_release='dist_release',
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/orchestrator/context/test_toolbelt.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/context/test_toolbelt.py b/tests/orchestrator/context/test_toolbelt.py
index da46696..b63811b 100644
--- a/tests/orchestrator/context/test_toolbelt.py
+++ b/tests/orchestrator/context/test_toolbelt.py
@@ -49,21 +49,21 @@ def executor():
def _get_elements(workflow_context):
dependency_node = workflow_context.model.node.get_by_name(mock.models.DEPENDENCY_NODE_NAME)
- dependency_node.host_id = dependency_node.id
+ dependency_node.host = dependency_node
workflow_context.model.node.update(dependency_node)
dependency_node_instance = workflow_context.model.node_instance.get_by_name(
mock.models.DEPENDENCY_NODE_INSTANCE_NAME)
- dependency_node_instance.host_id = dependency_node_instance.id
+ dependency_node_instance.host_fk = dependency_node_instance.id
workflow_context.model.node_instance.update(dependency_node_instance)
dependent_node = workflow_context.model.node.get_by_name(mock.models.DEPENDENT_NODE_NAME)
- dependent_node.host_id = dependency_node.id
+ dependent_node.host_fk = dependency_node.id
workflow_context.model.node.update(dependent_node)
dependent_node_instance = workflow_context.model.node_instance.get_by_name(
mock.models.DEPENDENT_NODE_INSTANCE_NAME)
- dependent_node_instance.host_id = dependent_node_instance.id
+ dependent_node_instance.host_fk = dependent_node_instance.id
workflow_context.model.node_instance.update(dependent_node_instance)
relationship = workflow_context.model.relationship.list()[0]
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/orchestrator/workflows/builtin/test_heal.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/builtin/test_heal.py b/tests/orchestrator/workflows/builtin/test_heal.py
index 97121b9..ad281fd 100644
--- a/tests/orchestrator/workflows/builtin/test_heal.py
+++ b/tests/orchestrator/workflows/builtin/test_heal.py
@@ -34,7 +34,7 @@ def ctx(tmpdir):
def test_heal_dependent_node(ctx):
dependent_node_instance = \
ctx.model.node_instance.get_by_name(mock.models.DEPENDENT_NODE_INSTANCE_NAME)
- dependent_node_instance.host_id = dependent_node_instance.id
+ dependent_node_instance.host_fk = dependent_node_instance.id
ctx.model.node_instance.update(dependent_node_instance)
heal_graph = task.WorkflowTask(heal, ctx=ctx, node_instance_id=dependent_node_instance.id)
@@ -63,7 +63,7 @@ def test_heal_dependent_node(ctx):
def test_heal_dependency_node(ctx):
dependency_node_instance = \
ctx.model.node_instance.get_by_name(mock.models.DEPENDENCY_NODE_INSTANCE_NAME)
- dependency_node_instance.host_id = dependency_node_instance.id
+ dependency_node_instance.host_fk = dependency_node_instance.id
ctx.model.node_instance.update(dependency_node_instance)
heal_graph = task.WorkflowTask(heal, ctx=ctx, node_instance_id=dependency_node_instance.id)
# both subgraphs should contain un\install for both the dependent and the dependency
[3/4] incubator-ariatosca git commit: Generifying ARIA models
Posted by mx...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/orchestrator/workflows/core/test_engine.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/core/test_engine.py b/tests/orchestrator/workflows/core/test_engine.py
index baded7f..a6b55ba 100644
--- a/tests/orchestrator/workflows/core/test_engine.py
+++ b/tests/orchestrator/workflows/core/test_engine.py
@@ -23,7 +23,7 @@ from aria.orchestrator import (
workflow,
operation,
)
-from aria.storage import models
+from aria.storage import model
from aria.orchestrator.workflows import (
api,
exceptions,
@@ -146,7 +146,7 @@ class TestEngine(BaseTest):
execution = workflow_context.execution
assert execution.started_at <= execution.ended_at <= datetime.utcnow()
assert execution.error is None
- assert execution.status == models.Execution.TERMINATED
+ assert execution.status == model.Execution.TERMINATED
def test_single_task_successful_execution(self, workflow_context, executor):
@workflow
@@ -175,7 +175,7 @@ class TestEngine(BaseTest):
execution = workflow_context.execution
assert execution.started_at <= execution.ended_at <= datetime.utcnow()
assert execution.error is not None
- assert execution.status == models.Execution.FAILED
+ assert execution.status == model.Execution.FAILED
def test_two_tasks_execution_order(self, workflow_context, executor):
@workflow
@@ -236,7 +236,7 @@ class TestCancel(BaseTest):
execution = workflow_context.execution
assert execution.started_at <= execution.ended_at <= datetime.utcnow()
assert execution.error is None
- assert execution.status == models.Execution.CANCELLED
+ assert execution.status == model.Execution.CANCELLED
def test_cancel_pending_execution(self, workflow_context, executor):
@workflow
@@ -247,7 +247,7 @@ class TestCancel(BaseTest):
executor=executor)
eng.cancel_execution()
execution = workflow_context.execution
- assert execution.status == models.Execution.CANCELLED
+ assert execution.status == model.Execution.CANCELLED
class TestRetries(BaseTest):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/orchestrator/workflows/executor/test_executor.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/executor/test_executor.py b/tests/orchestrator/workflows/executor/test_executor.py
index 7a11524..ff4b8b2 100644
--- a/tests/orchestrator/workflows/executor/test_executor.py
+++ b/tests/orchestrator/workflows/executor/test_executor.py
@@ -21,6 +21,8 @@ from contextlib import contextmanager
import pytest
import retrying
+from aria.storage import model
+
try:
import celery as _celery
app = _celery.Celery()
@@ -30,7 +32,6 @@ except ImportError:
app = None
import aria
-from aria.storage import models
from aria.orchestrator import events
from aria.orchestrator.workflows.executor import (
thread,
@@ -82,7 +83,7 @@ class MockException(Exception):
class MockTask(object):
- INFINITE_RETRIES = models.Task.INFINITE_RETRIES
+ INFINITE_RETRIES = model.Task.INFINITE_RETRIES
def __init__(self, func, inputs=None, ctx=None):
self.states = []
@@ -99,7 +100,7 @@ class MockTask(object):
self.max_attempts = 1
self.plugin_id = None
- for state in models.Task.STATES:
+ for state in model.Task.STATES:
setattr(self, state.upper(), state)
@contextmanager
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/orchestrator/workflows/executor/test_process_executor.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/executor/test_process_executor.py b/tests/orchestrator/workflows/executor/test_process_executor.py
index 364d354..2e4af1f 100644
--- a/tests/orchestrator/workflows/executor/test_process_executor.py
+++ b/tests/orchestrator/workflows/executor/test_process_executor.py
@@ -22,7 +22,7 @@ from contextlib import contextmanager
import pytest
from aria import application_model_storage
-from aria.storage import models
+from aria.storage import model as aria_model
from aria.utils.plugin import create as create_plugin
from aria.storage.sql_mapi import SQLAlchemyModelAPI
from aria.orchestrator import events
@@ -108,7 +108,7 @@ def mock_plugin(plugin_manager, tmpdir):
class MockTask(object):
- INFINITE_RETRIES = models.Task.INFINITE_RETRIES
+ INFINITE_RETRIES = aria_model.Task.INFINITE_RETRIES
def __init__(self, plugin, operation):
self.id = str(uuid.uuid4())
@@ -122,7 +122,7 @@ class MockTask(object):
self.plugin_id = plugin.id
self.plugin = plugin
- for state in models.Task.STATES:
+ for state in aria_model.Task.STATES:
setattr(self, state.upper(), state)
@contextmanager
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/storage/__init__.py
----------------------------------------------------------------------
diff --git a/tests/storage/__init__.py b/tests/storage/__init__.py
index edff982..9101fd0 100644
--- a/tests/storage/__init__.py
+++ b/tests/storage/__init__.py
@@ -17,14 +17,13 @@ import platform
from tempfile import mkdtemp
from shutil import rmtree
+from aria.storage import model
from sqlalchemy import (
create_engine,
orm)
from sqlalchemy.orm import scoped_session
from sqlalchemy.pool import StaticPool
-from aria.storage import structures
-
class TestFileSystem(object):
@@ -60,7 +59,7 @@ def get_sqlite_api_kwargs(base_dir=None, filename='db.sqlite'):
session_factory = orm.sessionmaker(bind=engine)
session = scoped_session(session_factory=session_factory) if base_dir else session_factory()
- structures.Model.metadata.create_all(engine)
+ model.DeclarativeBase.metadata.create_all(bind=engine)
return dict(engine=engine, session=session)
@@ -77,4 +76,4 @@ def release_sqlite_storage(storage):
session.rollback()
session.close()
for engine in set(mapi._engine for mapi in mapis):
- structures.Model.metadata.drop_all(engine)
+ model.DeclarativeBase.metadata.drop_all(engine)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/storage/test_model_storage.py
----------------------------------------------------------------------
diff --git a/tests/storage/test_model_storage.py b/tests/storage/test_model_storage.py
index 48cd02c..43dfa1b 100644
--- a/tests/storage/test_model_storage.py
+++ b/tests/storage/test_model_storage.py
@@ -15,64 +15,75 @@
import pytest
+from sqlalchemy import Column, Text, Integer
+
from aria.storage import (
ModelStorage,
- models,
+ model,
exceptions,
sql_mapi,
+ structure,
+ type as aria_type,
)
from aria import application_model_storage
from tests.storage import get_sqlite_api_kwargs, release_sqlite_storage
+class MockModel(model.DeclarativeBase, structure.ModelMixin): #pylint: disable=abstract-method
+ __tablename__ = 'mock_models'
+ some_dict = Column(aria_type.Dict)
+ value = Column(Integer)
+ name = Column(Text)
+
+
@pytest.fixture
def storage():
base_storage = ModelStorage(sql_mapi.SQLAlchemyModelAPI, api_kwargs=get_sqlite_api_kwargs())
+ base_storage.register(MockModel)
yield base_storage
release_sqlite_storage(base_storage)
+@pytest.fixture(scope='module', autouse=True)
+def module_cleanup():
+ model.DeclarativeBase.metadata.remove(MockModel.__table__) #pylint: disable=no-member
+
+
def test_storage_base(storage):
with pytest.raises(AttributeError):
storage.non_existent_attribute()
def test_model_storage(storage):
- storage.register(models.ProviderContext)
+ mock_model = MockModel(value=0, name='model_name')
+ storage.mock_model.put(mock_model)
- pc = models.ProviderContext(context={}, name='context_name')
- storage.provider_context.put(pc)
+ assert storage.mock_model.get_by_name('model_name') == mock_model
- assert storage.provider_context.get_by_name('context_name') == pc
+ assert [mm_from_storage for mm_from_storage in storage.mock_model.iter()] == [mock_model]
+ assert [mm_from_storage for mm_from_storage in storage.mock_model] == [mock_model]
- assert [pc_from_storage for pc_from_storage in storage.provider_context.iter()] == [pc]
- assert [pc_from_storage for pc_from_storage in storage.provider_context] == [pc]
-
- new_context = {'update_key': 0}
- pc.context = new_context
- storage.provider_context.update(pc)
- assert storage.provider_context.get(pc.id).context == new_context
-
- storage.provider_context.delete(pc)
+ storage.mock_model.delete(mock_model)
with pytest.raises(exceptions.StorageError):
- storage.provider_context.get(pc.id)
+ storage.mock_model.get(mock_model.id)
-def test_storage_driver(storage):
- storage.register(models.ProviderContext)
+def test_inner_dict_update(storage):
+ inner_dict = {'inner_value': 1}
- pc = models.ProviderContext(context={}, name='context_name')
- storage.registered['provider_context'].put(entry=pc)
+ mock_model = MockModel(some_dict={'inner_dict': inner_dict, 'value': 0})
+ storage.mock_model.put(mock_model)
- assert storage.registered['provider_context'].get_by_name('context_name') == pc
+ storage_mm = storage.mock_model.get(mock_model.id)
+ assert storage_mm == mock_model
- assert next(i for i in storage.registered['provider_context'].iter()) == pc
- assert [i for i in storage.provider_context] == [pc]
+ storage_mm.some_dict['inner_dict']['inner_value'] = 2
+ storage_mm.some_dict['value'] = -1
+ storage.mock_model.update(storage_mm)
+ storage_mm = storage.mock_model.get(storage_mm.id)
- storage.registered['provider_context'].delete(pc)
-
- with pytest.raises(exceptions.StorageError):
- storage.registered['provider_context'].get(pc.id)
+ assert storage_mm.some_dict['inner_dict']['inner_value'] == 2
+ assert storage_mm.some_dict['value'] == -1
def test_application_storage_factory():
@@ -87,6 +98,5 @@ def test_application_storage_factory():
assert storage.deployment_update_step
assert storage.deployment_modification
assert storage.execution
- assert storage.provider_context
release_sqlite_storage(storage)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/6e1f1260/tests/storage/test_models.py
----------------------------------------------------------------------
diff --git a/tests/storage/test_models.py b/tests/storage/test_models.py
index 0651957..c4836a6 100644
--- a/tests/storage/test_models.py
+++ b/tests/storage/test_models.py
@@ -12,19 +12,21 @@
# 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 contextlib import contextmanager
from datetime import datetime
+from contextlib import contextmanager
+
import pytest
from aria import application_model_storage
-from aria.storage import exceptions
-from aria.storage import sql_mapi
-from aria.storage.models import (
+from aria.storage import (
+ exceptions,
+ sql_mapi,
+)
+from aria.storage.model import (
DeploymentUpdateStep,
Blueprint,
Execution,
Task,
- ProviderContext,
Plugin,
Deployment,
Node,
@@ -73,7 +75,7 @@ def _deployment_storage():
def _deployment_update_storage():
storage = _deployment_storage()
deployment_update = DeploymentUpdate(
- deployment_id=storage.deployment.list()[0].id,
+ deployment=storage.deployment.list()[0],
created_at=now,
deployment_plan={},
)
@@ -194,15 +196,15 @@ class TestBlueprint(object):
)
def test_blueprint_model_creation(self, empty_storage, is_valid, plan, description, created_at,
updated_at, main_file_name):
- if not is_valid:
- with pytest.raises(exceptions.StorageError):
- empty_storage.blueprint.put(Blueprint(plan=plan, description=description,
- created_at=created_at, updated_at=updated_at,
- main_file_name=main_file_name))
- else:
- empty_storage.blueprint.put(Blueprint(plan=plan, description=description,
- created_at=created_at, updated_at=updated_at,
- main_file_name=main_file_name))
+ _test_model(is_valid=is_valid,
+ storage=empty_storage,
+ model_name='blueprint',
+ model_cls=Blueprint,
+ model_kwargs=dict(plan=plan,
+ description=description,
+ created_at=created_at,
+ updated_at=updated_at,
+ main_file_name=main_file_name))
class TestDeployment(object):
@@ -211,32 +213,32 @@ class TestDeployment(object):
'is_valid, name, created_at, description, inputs, groups, permalink, policy_triggers, '
'policy_types, outputs, scaling_groups, updated_at, workflows',
[
- (False, m_cls, now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (False, 'name', m_cls, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (False, 'name', now, m_cls, {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (False, 'name', now, 'desc', m_cls, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (False, 'name', now, 'desc', {}, m_cls, 'perlnk', {}, {}, {}, {}, now, {}),
- (False, 'name', now, 'desc', {}, {}, m_cls, {}, {}, {}, {}, now, {}),
- (False, 'name', now, 'desc', {}, {}, 'perlnk', m_cls, {}, {}, {}, now, {}),
- (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, m_cls, {}, {}, now, {}),
- (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, m_cls, {}, now, {}),
+ (False, m_cls, now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (False, 'name', m_cls, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (False, 'name', now, m_cls, {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (False, 'name', now, 'desc', m_cls, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (False, 'name', now, 'desc', {}, m_cls, 'perlnk', {}, {}, {}, [], now, {}),
+ (False, 'name', now, 'desc', {}, {}, m_cls, {}, {}, {}, [], now, {}),
+ (False, 'name', now, 'desc', {}, {}, 'perlnk', m_cls, {}, {}, [], now, {}),
+ (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, m_cls, {}, [], now, {}),
+ (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, m_cls, [], now, {}),
(False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, m_cls, now, {}),
- (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, m_cls, {}),
- (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, m_cls),
-
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, None, now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, 'name', now, None, {}, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', None, {}, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, None, 'perlnk', {}, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, {}, None, {}, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', None, {}, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, None, {}, {}, now, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, None, {}, now, {}),
+ (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], m_cls, {}),
+ (False, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, m_cls),
+
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, None, now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, 'name', now, None, {}, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', None, {}, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, None, 'perlnk', {}, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, {}, None, {}, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', None, {}, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, None, {}, [], now, {}),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, None, [], now, {}),
(True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, None, now, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, None, {}),
- (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, {}, now, None),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], None, {}),
+ (True, 'name', now, 'desc', {}, {}, 'perlnk', {}, {}, {}, [], now, None),
]
)
def test_deployment_model_creation(self, deployment_storage, is_valid, name, created_at,
@@ -249,7 +251,7 @@ class TestDeployment(object):
model_cls=Deployment,
model_kwargs=dict(
name=name,
- blueprint_id=deployment_storage.blueprint.list()[0].id,
+ blueprint=deployment_storage.blueprint.list()[0],
created_at=created_at,
description=description,
inputs=inputs,
@@ -295,8 +297,7 @@ class TestExecution(object):
model_name='execution',
model_cls=Execution,
model_kwargs=dict(
- deployment_id=deployment_storage.deployment.list()[0].id,
- blueprint_id=deployment_storage.blueprint.list()[0].id,
+ deployment=deployment_storage.deployment.list()[0],
created_at=created_at,
started_at=started_at,
ended_at=ended_at,
@@ -406,7 +407,7 @@ class TestDeploymentUpdate(object):
model_name='deployment_update',
model_cls=DeploymentUpdate,
model_kwargs=dict(
- deployment_id=deployment_storage.deployment.list()[0].id,
+ deployment=deployment_storage.deployment.list()[0],
created_at=created_at,
deployment_plan=deployment_plan,
deployment_update_node_instances=deployment_update_node_instances,
@@ -441,7 +442,7 @@ class TestDeploymentUpdateStep(object):
model_name='deployment_update_step',
model_cls=DeploymentUpdateStep,
model_kwargs=dict(
- deployment_update_id=deployment_update_storage.deployment_update.list()[0].id,
+ deployment_update=deployment_update_storage.deployment_update.list()[0],
action=action,
entity_id=entity_id,
entity_type=entity_type
@@ -517,7 +518,7 @@ class TestDeploymentModification(object):
model_name='deployment_modification',
model_cls=DeploymentModification,
model_kwargs=dict(
- deployment_id=deployment_storage.deployment.list()[0].id,
+ deployment=deployment_storage.deployment.list()[0],
context=context,
created_at=created_at,
ended_at=ended_at,
@@ -576,7 +577,7 @@ class TestNode(object):
operations=operations,
type=type,
type_hierarchy=type_hierarchy,
- deployment_id=deployment_storage.deployment.list()[0].id
+ deployment=deployment_storage.deployment.list()[0]
))
if is_valid:
assert node.deployment == deployment_storage.deployment.list()[0]
@@ -611,8 +612,8 @@ class TestRelationship(object):
model_name='relationship',
model_cls=Relationship,
model_kwargs=dict(
- source_node_id=nodes_storage.node.list()[1].id,
- target_node_id=nodes_storage.node.list()[0].id,
+ source_node=nodes_storage.node.list()[1],
+ target_node=nodes_storage.node.list()[0],
source_interfaces=source_interfaces,
source_operations=source_operations,
target_interfaces=target_interfaces,
@@ -651,8 +652,7 @@ class TestNodeInstance(object):
model_name='node_instance',
model_cls=NodeInstance,
model_kwargs=dict(
- node_id=node_storage.node.list()[0].id,
- deployment_id=node_storage.deployment.list()[0].id,
+ node=node_storage.node.list()[0],
name=name,
runtime_properties=runtime_properties,
scaling_groups=scaling_groups,
@@ -681,33 +681,15 @@ class TestRelationshipInstance(object):
model_name='relationship_instance',
model_cls=RelationshipInstance,
model_kwargs=dict(
- relationship_id=relationship.id,
- source_node_instance_id=source_node_instance.id,
- target_node_instance_id=target_node_instance.id
+ relationship=relationship,
+ source_node_instance=source_node_instance,
+ target_node_instance=target_node_instance
))
assert relationship_instance.relationship == relationship
assert relationship_instance.source_node_instance == source_node_instance
assert relationship_instance.target_node_instance == target_node_instance
-class TestProviderContext(object):
- @pytest.mark.parametrize(
- 'is_valid, name, context',
- [
- (False, None, {}),
- (False, 'name', None),
- (True, 'name', {}),
- ]
- )
- def test_provider_context_model_creation(self, empty_storage, is_valid, name, context):
- _test_model(is_valid=is_valid,
- storage=empty_storage,
- model_name='provider_context',
- model_cls=ProviderContext,
- model_kwargs=dict(name=name, context=context)
- )
-
-
class TestPlugin(object):
@pytest.mark.parametrize(
'is_valid, archive_name, distribution, distribution_release, '
@@ -715,48 +697,47 @@ class TestPlugin(object):
'package_version, supported_platform, supported_py_versions, uploaded_at, wheels',
[
(False, m_cls, 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', m_cls, 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', m_cls, 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', m_cls, 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', m_cls, 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', m_cls, 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', m_cls,
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
'pak_ver', m_cls, [], now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', m_cls, now, []),
+ 'pak_ver', 'sup_plat', m_cls, now, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', [], m_cls, []),
+ 'pak_ver', 'sup_plat', [], m_cls, []),
(False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', [], now, m_cls),
+ 'pak_ver', 'sup_plat', [], now, m_cls),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver', 'sup_plat', [], now, []),
(True, 'arc_name', None, 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(True, 'arc_name', 'dis_name', None, 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', None, 'pak_name', 'pak_src', 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', [], now, []),
+ 'pak_ver', 'sup_plat', {}, now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', None, 'pak_ver',
- 'sup_pla', [], now, []),
+ 'sup_plat', [], now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', None,
- 'sup_pla', [], now, []),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', None, [], now, []),
+ 'sup_plat', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', None, {}, now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', None, now, []),
+ 'pak_ver', 'sup_plat', None, now, []),
(True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
- 'pak_ver', 'sup_pla', [], now, []),
+ 'pak_ver', 'sup_plat', [], now, []),
]
)
def test_plugin_model_creation(self, empty_storage, is_valid, archive_name, distribution,
@@ -823,7 +804,7 @@ class TestTask(object):
model_cls=Task,
model_kwargs=dict(
status=status,
- execution_id=execution_storage.execution.list()[0].id,
+ execution=execution_storage.execution.list()[0],
due_at=due_at,
started_at=started_at,
ended_at=ended_at,
@@ -834,16 +815,16 @@ class TestTask(object):
name=name,
operation_mapping=operation_mapping,
inputs=inputs,
- plugin_id=plugin_id,
+ plugin_fk=plugin_id,
))
if is_valid:
assert task.execution == execution_storage.execution.list()[0]
- if task.plugin_id:
+ if task.plugin:
assert task.plugin == execution_storage.plugin.list()[0]
def test_task_max_attempts_validation(self):
def create_task(max_attempts):
- Task(execution_id='eid',
+ Task(execution_fk='eid',
name='name',
operation_mapping='',
inputs={},
@@ -855,23 +836,3 @@ class TestTask(object):
create_task(max_attempts=0)
with pytest.raises(ValueError):
create_task(max_attempts=-2)
-
-
-def test_inner_dict_update(empty_storage):
- inner_dict = {'inner_value': 1}
- pc = ProviderContext(name='name', context={
- 'inner_dict': {'inner_value': inner_dict},
- 'value': 0
- })
- empty_storage.provider_context.put(pc)
-
- storage_pc = empty_storage.provider_context.get(pc.id)
- assert storage_pc == pc
-
- storage_pc.context['inner_dict']['inner_value'] = 2
- storage_pc.context['value'] = -1
- empty_storage.provider_context.update(storage_pc)
- storage_pc = empty_storage.provider_context.get(pc.id)
-
- assert storage_pc.context['inner_dict']['inner_value'] == 2
- assert storage_pc.context['value'] == -1
[2/4] incubator-ariatosca git commit: ARIA-26 Implement operation
plugin mechanism
Posted by mx...@apache.org.
ARIA-26 Implement operation plugin mechanism
Project: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/commit/5cf84eeb
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/tree/5cf84eeb
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/diff/5cf84eeb
Branch: refs/heads/ARIA-39-Genericize-storage-models
Commit: 5cf84eebe425bbade0d9285081cebf5d0a62a675
Parents: 04c9bd0
Author: Dan Kilman <da...@gigaspaces.com>
Authored: Sun Nov 27 16:31:29 2016 +0200
Committer: Dan Kilman <da...@gigaspaces.com>
Committed: Mon Dec 19 15:47:38 2016 +0200
----------------------------------------------------------------------
aria/cli/commands.py | 4 +-
aria/orchestrator/exceptions.py | 7 +
aria/orchestrator/plugin.py | 105 +++++++
aria/orchestrator/workflows/api/task.py | 44 ++-
aria/orchestrator/workflows/core/task.py | 12 +-
.../orchestrator/workflows/executor/__init__.py | 2 +-
aria/orchestrator/workflows/executor/base.py | 6 +-
.../orchestrator/workflows/executor/blocking.py | 36 ---
.../workflows/executor/multiprocess.py | 98 -------
aria/orchestrator/workflows/executor/process.py | 277 +++++++++++++++++++
aria/orchestrator/workflows/executor/thread.py | 4 +-
aria/storage/models.py | 15 +-
aria/utils/plugin.py | 20 ++
requirements.txt | 3 +-
tests/mock/models.py | 16 ++
tests/orchestrator/workflows/api/test_task.py | 51 +++-
tests/orchestrator/workflows/core/test_task.py | 16 +-
.../workflows/executor/test_executor.py | 111 ++++----
.../workflows/executor/test_process_executor.py | 130 +++++++++
tests/resources/__init__.py | 19 ++
.../plugins/mock-plugin1/mock_plugin1.py | 27 ++
tests/resources/plugins/mock-plugin1/setup.py | 28 ++
tests/storage/test_models.py | 188 ++++++-------
tests/utils/__init__.py | 14 +
tests/utils/test_plugin.py | 77 ++++++
25 files changed, 990 insertions(+), 320 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/cli/commands.py
----------------------------------------------------------------------
diff --git a/aria/cli/commands.py b/aria/cli/commands.py
index 141da07..1cd765f 100644
--- a/aria/cli/commands.py
+++ b/aria/cli/commands.py
@@ -34,7 +34,7 @@ from ..logger import LoggerMixin
from ..storage import (FileSystemModelDriver, FileSystemResourceDriver)
from ..orchestrator.context.workflow import WorkflowContext
from ..orchestrator.workflows.core.engine import Engine
-from ..orchestrator.workflows.executor.thread import ThreadExecutor
+from ..orchestrator.workflows.executor.process import ProcessExecutor
from ..parser import iter_specifications
from ..parser.consumption import (
ConsumptionContext,
@@ -252,7 +252,7 @@ class ExecuteCommand(BaseCommand):
)
workflow_function = self._load_workflow_handler(workflow['operation'])
tasks_graph = workflow_function(workflow_context, **workflow_context.parameters)
- executor = ThreadExecutor()
+ executor = ProcessExecutor()
workflow_engine = Engine(executor=executor,
workflow_context=workflow_context,
tasks_graph=tasks_graph)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/exceptions.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/exceptions.py b/aria/orchestrator/exceptions.py
index 1a48194..74e9002 100644
--- a/aria/orchestrator/exceptions.py
+++ b/aria/orchestrator/exceptions.py
@@ -23,3 +23,10 @@ class OrchestratorError(AriaError):
Orchestrator based exception
"""
pass
+
+
+class PluginAlreadyExistsError(AriaError):
+ """
+ Raised when a plugin with the same package name and package version already exists
+ """
+ pass
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/plugin.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/plugin.py b/aria/orchestrator/plugin.py
new file mode 100644
index 0000000..3005756
--- /dev/null
+++ b/aria/orchestrator/plugin.py
@@ -0,0 +1,105 @@
+# 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.
+
+import os
+import tempfile
+import subprocess
+import sys
+from datetime import datetime
+
+import wagon
+
+from . import exceptions
+
+
+class PluginManager(object):
+
+ def __init__(self, model, plugins_dir):
+ """
+ :param plugins_dir: Root directory to install plugins in.
+ """
+ self._model = model
+ self._plugins_dir = plugins_dir
+
+ def install(self, source):
+ """
+ Install a wagon plugin.
+ """
+ metadata = wagon.show(source)
+ cls = self._model.plugin.model_cls
+ plugin = cls(
+ archive_name=metadata['archive_name'],
+ supported_platform=metadata['supported_platform'],
+ supported_py_versions=metadata['supported_python_versions'],
+ # Remove suffix colon after upgrading wagon to > 0.5.0
+ distribution=metadata['build_server_os_properties']['distribution:'],
+ distribution_release=metadata['build_server_os_properties']['distribution_version'],
+ distribution_version=metadata['build_server_os_properties']['distribution_release'],
+ package_name=metadata['package_name'],
+ package_version=metadata['package_version'],
+ package_source=metadata['package_source'],
+ wheels=metadata['wheels'],
+ uploaded_at=datetime.now()
+ )
+ if len(self._model.plugin.list(filters={'package_name': plugin.package_name,
+ 'package_version': plugin.package_version})):
+ raise exceptions.PluginAlreadyExistsError(
+ 'Plugin {0}, version {1} already exists'.format(plugin.package_name,
+ plugin.package_version))
+ self._install_wagon(source=source, prefix=self.get_plugin_prefix(plugin))
+ self._model.plugin.put(plugin)
+ return plugin
+
+ def get_plugin_prefix(self, plugin):
+ return os.path.join(
+ self._plugins_dir,
+ '{0}-{1}'.format(plugin.package_name, plugin.package_version))
+
+ def _install_wagon(self, source, prefix):
+ pip_freeze_output = self._pip_freeze()
+ file_descriptor, constraint_path = tempfile.mkstemp(prefix='constraint-', suffix='.txt')
+ os.close(file_descriptor)
+ try:
+ with open(constraint_path, 'wb') as constraint:
+ constraint.write(pip_freeze_output)
+ # Install the provided wagon.
+ # * The --prefix install_arg will cause the plugin to be installed under
+ # plugins_dir/{package_name}-{package_version}, So different plugins don't step on
+ # each other and don't interfere with the current virtualenv
+ # * The --constraint flag points a file containing the output of ``pip freeze``.
+ # It is required, to handle cases where plugins depend on some python package with
+ # a different version than the one installed in the current virtualenv. Without this
+ # flag, the existing package will be **removed** from the parent virtualenv and the
+ # new package will be installed under prefix. With the flag, the existing version will
+ # remain, and the version requested by the plugin will be ignored.
+ wagon.install(
+ source=source,
+ install_args='--prefix="{prefix}" --constraint="{constraint}"'.format(
+ prefix=prefix,
+ constraint=constraint.name),
+ virtualenv=os.environ.get('VIRTUAL_ENV'))
+ finally:
+ os.remove(constraint_path)
+
+ @staticmethod
+ def _pip_freeze():
+ """Run pip freeze in current environment and return the output"""
+ bin_dir = 'Scripts' if os.name == 'nt' else 'bin'
+ pip_path = os.path.join(sys.prefix, bin_dir,
+ 'pip{0}'.format('.exe' if os.name == 'nt' else ''))
+ pip_freeze = subprocess.Popen([pip_path, 'freeze'], stdout=subprocess.PIPE)
+ pip_freeze_output, _ = pip_freeze.communicate()
+ assert not pip_freeze.poll()
+ return pip_freeze_output
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/api/task.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/api/task.py b/aria/orchestrator/workflows/api/task.py
index 1c12407..4f025b6 100644
--- a/aria/orchestrator/workflows/api/task.py
+++ b/aria/orchestrator/workflows/api/task.py
@@ -67,11 +67,11 @@ class OperationTask(BaseTask):
max_attempts=None,
retry_interval=None,
ignore_failure=None,
- inputs=None):
+ inputs=None,
+ plugin=None):
"""
Creates an operation task using the name, details, node instance and any additional kwargs.
:param name: the operation of the name.
- :param operation_details: the details for the operation.
:param actor: the operation host on which this operation is registered.
:param inputs: operation inputs.
"""
@@ -82,6 +82,7 @@ class OperationTask(BaseTask):
self.name = '{name}.{actor.id}'.format(name=name, actor=actor)
self.operation_mapping = operation_mapping
self.inputs = inputs or {}
+ self.plugin = plugin or {}
self.max_attempts = (self.workflow_context._task_max_attempts
if max_attempts is None else max_attempts)
self.retry_interval = (self.workflow_context._task_retry_interval
@@ -98,15 +99,13 @@ class OperationTask(BaseTask):
:param name: the name of the operation.
"""
assert isinstance(instance, models.NodeInstance)
- operation_details = instance.node.operations[name]
- operation_inputs = operation_details.get('inputs', {})
- operation_inputs.update(inputs or {})
- return cls(name=name,
- actor=instance,
- operation_mapping=operation_details.get('operation', ''),
- inputs=operation_inputs,
- *args,
- **kwargs)
+ return cls._instance(instance=instance,
+ name=name,
+ operation_details=instance.node.operations[name],
+ inputs=inputs,
+ plugins=instance.node.plugins or [],
+ *args,
+ **kwargs)
@classmethod
def relationship_instance(cls, instance, name, operation_end, inputs=None, *args, **kwargs):
@@ -125,12 +124,33 @@ class OperationTask(BaseTask):
cls.TARGET_OPERATION, cls.SOURCE_OPERATION
))
operation_details = getattr(instance.relationship, operation_end)[name]
+ if operation_end == cls.SOURCE_OPERATION:
+ plugins = instance.relationship.source_node.plugins
+ else:
+ plugins = instance.relationship.target_node.plugins
+ return cls._instance(instance=instance,
+ name=name,
+ operation_details=operation_details,
+ inputs=inputs,
+ plugins=plugins or [],
+ *args,
+ **kwargs)
+
+ @classmethod
+ def _instance(cls, instance, name, operation_details, inputs, plugins, *args, **kwargs):
+ operation_mapping = operation_details.get('operation')
operation_inputs = operation_details.get('inputs', {})
operation_inputs.update(inputs or {})
+ plugin_name = operation_details.get('plugin')
+ matching_plugins = [p for p in plugins if p['name'] == plugin_name]
+ # All matching plugins should have identical package_name/package_version, so it's safe to
+ # take the first found.
+ plugin = matching_plugins[0] if matching_plugins else {}
return cls(actor=instance,
name=name,
- operation_mapping=operation_details.get('operation'),
+ operation_mapping=operation_mapping,
inputs=operation_inputs,
+ plugin=plugin,
*args,
**kwargs)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/core/task.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/core/task.py b/aria/orchestrator/workflows/core/task.py
index 0be17fe..08cf26e 100644
--- a/aria/orchestrator/workflows/core/task.py
+++ b/aria/orchestrator/workflows/core/task.py
@@ -106,8 +106,9 @@ class OperationTask(BaseTask):
def __init__(self, api_task, *args, **kwargs):
super(OperationTask, self).__init__(id=api_task.id, **kwargs)
self._workflow_context = api_task._workflow_context
- base_task_model = api_task._workflow_context.model.task.model_cls
+ model = api_task._workflow_context.model
+ base_task_model = model.task.model_cls
if isinstance(api_task.actor, models.NodeInstance):
context_class = operation_context.NodeOperationContext
task_model_cls = base_task_model.as_node_instance
@@ -117,7 +118,13 @@ class OperationTask(BaseTask):
else:
raise RuntimeError('No operation context could be created for {actor.model_cls}'
.format(actor=api_task.actor))
-
+ plugin = api_task.plugin
+ plugins = model.plugin.list(filters={'package_name': plugin.get('package_name', ''),
+ 'package_version': plugin.get('package_version', '')},
+ include=['id'])
+ # Validation during installation ensures that at most one plugin can exists with provided
+ # package_name and package_version
+ plugin_id = plugins[0].id if plugins else None
operation_task = task_model_cls(
name=api_task.name,
operation_mapping=api_task.operation_mapping,
@@ -127,6 +134,7 @@ class OperationTask(BaseTask):
max_attempts=api_task.max_attempts,
retry_interval=api_task.retry_interval,
ignore_failure=api_task.ignore_failure,
+ plugin_id=plugin_id
)
self._workflow_context.model.task.put(operation_task)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/__init__.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/__init__.py b/aria/orchestrator/workflows/executor/__init__.py
index 16b6c9b..414a740 100644
--- a/aria/orchestrator/workflows/executor/__init__.py
+++ b/aria/orchestrator/workflows/executor/__init__.py
@@ -18,5 +18,5 @@ Executors for task execution
"""
-from . import blocking, multiprocess, thread
+from . import process, thread
from .base import BaseExecutor
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/base.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/base.py b/aria/orchestrator/workflows/executor/base.py
index ba44124..4ae046d 100644
--- a/aria/orchestrator/workflows/executor/base.py
+++ b/aria/orchestrator/workflows/executor/base.py
@@ -17,17 +17,15 @@
Base executor module
"""
+from aria import logger
from aria.orchestrator import events
-class BaseExecutor(object):
+class BaseExecutor(logger.LoggerMixin):
"""
Base class for executors for running tasks
"""
- def __init__(self, *args, **kwargs):
- pass
-
def execute(self, task):
"""
Execute a task
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/blocking.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/blocking.py b/aria/orchestrator/workflows/executor/blocking.py
deleted file mode 100644
index 9d3a9ba..0000000
--- a/aria/orchestrator/workflows/executor/blocking.py
+++ /dev/null
@@ -1,36 +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.
-
-"""
-Blocking executor
-"""
-
-from aria.utils import imports
-from .base import BaseExecutor
-
-
-class CurrentThreadBlockingExecutor(BaseExecutor):
- """
- Executor which runs tasks in the current thread (blocking)
- """
-
- def execute(self, task):
- self._task_started(task)
- try:
- task_func = imports.load_attribute(task.operation_mapping)
- task_func(ctx=task.context, **task.inputs)
- self._task_succeeded(task)
- except BaseException as e:
- self._task_failed(task, exception=e)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/multiprocess.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/multiprocess.py b/aria/orchestrator/workflows/executor/multiprocess.py
deleted file mode 100644
index d770e07..0000000
--- a/aria/orchestrator/workflows/executor/multiprocess.py
+++ /dev/null
@@ -1,98 +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.
-
-"""
-Multiprocess based executor
-"""
-
-import multiprocessing
-import threading
-
-import jsonpickle
-
-from aria.utils import imports
-from .base import BaseExecutor
-
-
-class MultiprocessExecutor(BaseExecutor):
- """
- Executor which runs tasks in a multiprocess environment
- """
-
- def __init__(self, pool_size=1, *args, **kwargs):
- super(MultiprocessExecutor, self).__init__(*args, **kwargs)
- self._stopped = False
- self._manager = multiprocessing.Manager()
- self._queue = self._manager.Queue()
- self._tasks = {}
- self._listener_thread = threading.Thread(target=self._listener)
- self._listener_thread.daemon = True
- self._listener_thread.start()
- self._pool = multiprocessing.Pool(processes=pool_size)
-
- def execute(self, task):
- self._tasks[task.id] = task
- self._pool.apply_async(_multiprocess_handler, args=(
- self._queue,
- task.context,
- task.id,
- task.operation_mapping,
- task.inputs))
-
- def close(self):
- self._pool.close()
- self._stopped = True
- self._pool.join()
- self._listener_thread.join()
-
- def _listener(self):
- while not self._stopped:
- try:
- message = self._queue.get(timeout=1)
- if message.type == 'task_started':
- self._task_started(self._tasks[message.task_id])
- elif message.type == 'task_succeeded':
- self._task_succeeded(self._remove_task(message.task_id))
- elif message.type == 'task_failed':
- self._task_failed(self._remove_task(message.task_id),
- exception=jsonpickle.loads(message.exception))
- else:
- # TODO: something
- raise RuntimeError()
- # Daemon threads
- except BaseException:
- pass
-
- def _remove_task(self, task_id):
- return self._tasks.pop(task_id)
-
-
-class _MultiprocessMessage(object):
-
- def __init__(self, type, task_id, exception=None):
- self.type = type
- self.task_id = task_id
- self.exception = exception
-
-
-def _multiprocess_handler(queue, ctx, task_id, operation_mapping, operation_inputs):
- queue.put(_MultiprocessMessage(type='task_started', task_id=task_id))
- try:
- task_func = imports.load_attribute(operation_mapping)
- task_func(ctx=ctx, **operation_inputs)
- queue.put(_MultiprocessMessage(type='task_succeeded', task_id=task_id))
- except BaseException as e:
- queue.put(_MultiprocessMessage(type='task_failed', task_id=task_id,
- exception=jsonpickle.dumps(e)))
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/process.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/process.py b/aria/orchestrator/workflows/executor/process.py
new file mode 100644
index 0000000..1a47d4c
--- /dev/null
+++ b/aria/orchestrator/workflows/executor/process.py
@@ -0,0 +1,277 @@
+# 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.
+
+"""
+Subprocess based executor
+"""
+
+# pylint: disable=wrong-import-position
+
+import sys
+import os
+
+# As part of the process executor implementation, subprocess are started with this module as their
+# entry point. We thus remove this module's directory from the python path if it happens to be
+# there
+script_dir = os.path.dirname(__file__)
+if script_dir in sys.path:
+ sys.path.remove(script_dir)
+
+import io
+import threading
+import socket
+import struct
+import subprocess
+import tempfile
+import Queue
+
+import jsonpickle
+
+from aria.utils import imports
+from aria.orchestrator.workflows.executor import base
+
+_IS_WIN = os.name == 'nt'
+
+_INT_FMT = 'I'
+_INT_SIZE = struct.calcsize(_INT_FMT)
+
+
+class ProcessExecutor(base.BaseExecutor):
+ """
+ Executor which runs tasks in a subprocess environment
+ """
+
+ def __init__(self, plugin_manager=None, python_path=None, *args, **kwargs):
+ super(ProcessExecutor, self).__init__(*args, **kwargs)
+ self._plugin_manager = plugin_manager
+
+ # Optional list of additional directories that should be added to
+ # subprocesses python path
+ self._python_path = python_path or []
+
+ # Flag that denotes whether this executor has been stopped
+ self._stopped = False
+
+ # Contains reference to all currently running tasks
+ self._tasks = {}
+
+ # Server socket used to accept task status messages from subprocesses
+ self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._server_socket.bind(('localhost', 0))
+ self._server_socket.listen(10)
+ self._server_port = self._server_socket.getsockname()[1]
+
+ # Used to send a "closed" message to the listener when this executor is closed
+ self._messenger = _Messenger(task_id=None, port=self._server_port)
+
+ # Queue object used by the listener thread to notify this constructed it has started
+ # (see last line of this __init__ method)
+ self._listener_started = Queue.Queue()
+
+ # Listener thread to handle subprocesses task status messages
+ self._listener_thread = threading.Thread(target=self._listener)
+ self._listener_thread.daemon = True
+ self._listener_thread.start()
+
+ # Wait for listener thread to actually start before returning
+ self._listener_started.get(timeout=60)
+
+ def close(self):
+ if self._stopped:
+ return
+ self._stopped = True
+ # Listener thread may be blocked on "accept" call. This will wake it up with an explicit
+ # "closed" message
+ self._messenger.closed()
+ self._server_socket.close()
+ self._listener_thread.join(timeout=60)
+
+ def execute(self, task):
+ self._check_closed()
+ self._tasks[task.id] = task
+
+ # Temporary file used to pass arguments to the started subprocess
+ file_descriptor, arguments_json_path = tempfile.mkstemp(prefix='executor-', suffix='.json')
+ os.close(file_descriptor)
+ with open(arguments_json_path, 'wb') as f:
+ f.write(jsonpickle.dumps({
+ 'task_id': task.id,
+ 'operation_mapping': task.operation_mapping,
+ 'operation_inputs': task.inputs,
+ 'port': self._server_port
+ }))
+
+ env = os.environ.copy()
+ # See _update_env for plugin_prefix usage
+ if task.plugin_id and self._plugin_manager:
+ plugin_prefix = self._plugin_manager.get_plugin_prefix(task.plugin)
+ else:
+ plugin_prefix = None
+ self._update_env(env=env, plugin_prefix=plugin_prefix)
+ # Asynchronously start the operation in a subprocess
+ subprocess.Popen(
+ '{0} {1} {2}'.format(sys.executable, __file__, arguments_json_path),
+ env=env,
+ shell=True)
+
+ def _remove_task(self, task_id):
+ return self._tasks.pop(task_id)
+
+ def _listener(self):
+ # Notify __init__ method this thread has actually started
+ self._listener_started.put(True)
+ while not self._stopped:
+ try:
+ # Accept messages written to the server socket
+ message = self._recv_message()
+ message_type = message['type']
+ if message_type == 'closed':
+ break
+ task_id = message['task_id']
+ if message_type == 'started':
+ self._task_started(self._tasks[task_id])
+ elif message_type == 'succeeded':
+ self._task_succeeded(self._remove_task(task_id))
+ elif message_type == 'failed':
+ self._task_failed(self._remove_task(task_id),
+ exception=message['exception'])
+ else:
+ raise RuntimeError('Invalid state')
+ except BaseException as e:
+ self.logger.debug('Error in process executor listener: {0}'.format(e))
+
+ def _recv_message(self):
+ connection, _ = self._server_socket.accept()
+ try:
+ message_len, = struct.unpack(_INT_FMT, self._recv_bytes(connection, _INT_SIZE))
+ return jsonpickle.loads(self._recv_bytes(connection, message_len))
+ finally:
+ connection.close()
+
+ @staticmethod
+ def _recv_bytes(connection, count):
+ result = io.BytesIO()
+ while True:
+ if not count:
+ return result.getvalue()
+ read = connection.recv(count)
+ if not read:
+ return result.getvalue()
+ result.write(read)
+ count -= len(read)
+
+ def _check_closed(self):
+ if self._stopped:
+ raise RuntimeError('Executor closed')
+
+ def _update_env(self, env, plugin_prefix):
+ pythonpath_dirs = []
+ # If this is a plugin operation, plugin prefix will point to where
+ # This plugin is installed.
+ # We update the environment variables that the subprocess will be started with based on it
+ if plugin_prefix:
+
+ # Update PATH environment variable to include plugin's bin dir
+ bin_dir = 'Scripts' if _IS_WIN else 'bin'
+ env['PATH'] = '{0}{1}{2}'.format(
+ os.path.join(plugin_prefix, bin_dir),
+ os.pathsep,
+ env.get('PATH', ''))
+
+ # Update PYTHONPATH environment variable to include plugin's site-packages
+ # directories
+ if _IS_WIN:
+ pythonpath_dirs = [os.path.join(plugin_prefix, 'Lib', 'site-packages')]
+ else:
+ # In some linux environments, there will be both a lib and a lib64 directory
+ # with the latter, containing compiled packages.
+ pythonpath_dirs = [os.path.join(
+ plugin_prefix, 'lib{0}'.format(b),
+ 'python{0}.{1}'.format(sys.version_info[0], sys.version_info[1]),
+ 'site-packages') for b in ['', '64']]
+
+ # Add used supplied directories to injected PYTHONPATH
+ pythonpath_dirs.extend(self._python_path)
+
+ if pythonpath_dirs:
+ env['PYTHONPATH'] = '{0}{1}{2}'.format(
+ os.pathsep.join(pythonpath_dirs),
+ os.pathsep,
+ env.get('PYTHONPATH', ''))
+
+
+class _Messenger(object):
+
+ def __init__(self, task_id, port):
+ self.task_id = task_id
+ self.port = port
+
+ def started(self):
+ """Task started message"""
+ self._send_message(type='started')
+
+ def succeeded(self):
+ """Task succeeded message"""
+ self._send_message(type='succeeded')
+
+ def failed(self, exception):
+ """Task failed message"""
+ self._send_message(type='failed', exception=exception)
+
+ def closed(self):
+ """Executor closed message"""
+ self._send_message(type='closed')
+
+ def _send_message(self, type, exception=None):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect(('localhost', self.port))
+ try:
+ data = jsonpickle.dumps({
+ 'type': type,
+ 'task_id': self.task_id,
+ 'exception': exception
+ })
+ sock.send(struct.pack(_INT_FMT, len(data)))
+ sock.sendall(data)
+ finally:
+ sock.close()
+
+
+def _main():
+ arguments_json_path = sys.argv[1]
+ with open(arguments_json_path) as f:
+ arguments = jsonpickle.loads(f.read())
+
+ # arguments_json_path is a temporary file created by the parent process.
+ # so we remove it here
+ os.remove(arguments_json_path)
+
+ task_id = arguments['task_id']
+ port = arguments['port']
+ messenger = _Messenger(task_id=task_id, port=port)
+
+ operation_mapping = arguments['operation_mapping']
+ operation_inputs = arguments['operation_inputs']
+ ctx = None
+ messenger.started()
+ try:
+ task_func = imports.load_attribute(operation_mapping)
+ task_func(ctx=ctx, **operation_inputs)
+ messenger.succeeded()
+ except BaseException as e:
+ messenger.failed(exception=e)
+
+if __name__ == '__main__':
+ _main()
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/orchestrator/workflows/executor/thread.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/executor/thread.py b/aria/orchestrator/workflows/executor/thread.py
index 76ceefd..1a6ad9f 100644
--- a/aria/orchestrator/workflows/executor/thread.py
+++ b/aria/orchestrator/workflows/executor/thread.py
@@ -26,7 +26,9 @@ from .base import BaseExecutor
class ThreadExecutor(BaseExecutor):
"""
- Executor which runs tasks in a separate thread
+ Executor which runs tasks in a separate thread. It's easier writing tests
+ using this executor rather than the full blown subprocess executor.
+ Note: This executor is not capable of running plugin operations.
"""
def __init__(self, pool_size=1, *args, **kwargs):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/storage/models.py
----------------------------------------------------------------------
diff --git a/aria/storage/models.py b/aria/storage/models.py
index 6302e66..0a1027b 100644
--- a/aria/storage/models.py
+++ b/aria/storage/models.py
@@ -344,8 +344,7 @@ class Node(SQLModelBase):
min_number_of_instances = Column(Integer, nullable=False)
number_of_instances = Column(Integer, nullable=False)
planned_number_of_instances = Column(Integer, nullable=False)
- plugins = Column(Dict)
- plugins_to_install = Column(Dict)
+ plugins = Column(List)
properties = Column(Dict)
operations = Column(Dict)
type = Column(Text, nullable=False, index=True)
@@ -474,14 +473,13 @@ class Plugin(SQLModelBase):
distribution = Column(Text)
distribution_release = Column(Text)
distribution_version = Column(Text)
- excluded_wheels = Column(Dict)
package_name = Column(Text, nullable=False, index=True)
package_source = Column(Text)
package_version = Column(Text)
- supported_platform = Column(Dict)
- supported_py_versions = Column(Dict)
+ supported_platform = Column(Text)
+ supported_py_versions = Column(List)
uploaded_at = Column(DateTime, nullable=False, index=True)
- wheels = Column(Dict, nullable=False)
+ wheels = Column(List, nullable=False)
class Task(SQLModelBase):
@@ -550,6 +548,11 @@ class Task(SQLModelBase):
name = Column(String)
operation_mapping = Column(String)
inputs = Column(Dict)
+ plugin_id = foreign_key(Plugin.id, nullable=True)
+
+ @declared_attr
+ def plugin(cls):
+ return one_to_many_relationship(cls, Plugin, cls.plugin_id)
@declared_attr
def execution(cls):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/aria/utils/plugin.py
----------------------------------------------------------------------
diff --git a/aria/utils/plugin.py b/aria/utils/plugin.py
new file mode 100644
index 0000000..b7f94a1
--- /dev/null
+++ b/aria/utils/plugin.py
@@ -0,0 +1,20 @@
+# 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.
+
+import wagon
+
+
+def create(source, destination_dir):
+ return wagon.create(source=source, archive_destination_dir=destination_dir)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/requirements.txt
----------------------------------------------------------------------
diff --git a/requirements.txt b/requirements.txt
index 31b0b79..0005a5e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -24,4 +24,5 @@ Jinja2==2.8
shortuuid==0.4.3
CacheControl[filecache]==0.11.6
clint==0.5.1
-SQLAlchemy==1.1.4
\ No newline at end of file
+SQLAlchemy==1.1.4
+wagon==0.5.0
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/mock/models.py
----------------------------------------------------------------------
diff --git a/tests/mock/models.py b/tests/mock/models.py
index e2e3d2f..26088e0 100644
--- a/tests/mock/models.py
+++ b/tests/mock/models.py
@@ -152,3 +152,19 @@ def get_deployment(blueprint):
outputs={},
scaling_groups={},
)
+
+
+def get_plugin(package_name='package', package_version='0.1'):
+ return models.Plugin(
+ archive_name='archive_name',
+ distribution='distribution',
+ distribution_release='dist_release',
+ distribution_version='dist_version',
+ package_name=package_name,
+ package_source='source',
+ package_version=package_version,
+ supported_platform='any',
+ supported_py_versions=['python27'],
+ uploaded_at=datetime.now(),
+ wheels=[],
+ )
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/orchestrator/workflows/api/test_task.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/api/test_task.py b/tests/orchestrator/workflows/api/test_task.py
index 1a90338..58e387f 100644
--- a/tests/orchestrator/workflows/api/test_task.py
+++ b/tests/orchestrator/workflows/api/test_task.py
@@ -39,9 +39,12 @@ class TestOperationTask(object):
def test_node_operation_task_creation(self, ctx):
operation_name = 'aria.interfaces.lifecycle.create'
- op_details = {'operation': True}
+ op_details = {'operation': True, 'plugin': 'plugin'}
node = ctx.model.node.get_by_name(mock.models.DEPENDENT_NODE_NAME)
node.operations[operation_name] = op_details
+ node.plugins = [{'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}]
ctx.model.node.update(node)
node_instance = \
ctx.model.node_instance.get_by_name(mock.models.DEPENDENT_NODE_INSTANCE_NAME)
@@ -66,12 +69,18 @@ class TestOperationTask(object):
assert api_task.retry_interval == retry_interval
assert api_task.max_attempts == max_attempts
assert api_task.ignore_failure == ignore_failure
+ assert api_task.plugin == {'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}
- def test_relationship_operation_task_creation(self, ctx):
+ def test_source_relationship_operation_task_creation(self, ctx):
operation_name = 'aria.interfaces.relationship_lifecycle.preconfigure'
- op_details = {'operation': True}
+ op_details = {'operation': True, 'plugin': 'plugin'}
relationship = ctx.model.relationship.list()[0]
relationship.source_operations[operation_name] = op_details
+ relationship.source_node.plugins = [{'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}]
relationship_instance = ctx.model.relationship_instance.list()[0]
inputs = {'inputs': True}
max_attempts = 10
@@ -92,6 +101,41 @@ class TestOperationTask(object):
assert api_task.inputs == inputs
assert api_task.retry_interval == retry_interval
assert api_task.max_attempts == max_attempts
+ assert api_task.plugin == {'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}
+
+ def test_target_relationship_operation_task_creation(self, ctx):
+ operation_name = 'aria.interfaces.relationship_lifecycle.preconfigure'
+ op_details = {'operation': True, 'plugin': 'plugin'}
+ relationship = ctx.model.relationship.list()[0]
+ relationship.target_operations[operation_name] = op_details
+ relationship.target_node.plugins = [{'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}]
+ relationship_instance = ctx.model.relationship_instance.list()[0]
+ inputs = {'inputs': True}
+ max_attempts = 10
+ retry_interval = 10
+
+ with context.workflow.current.push(ctx):
+ api_task = api.task.OperationTask.relationship_instance(
+ name=operation_name,
+ instance=relationship_instance,
+ operation_end=api.task.OperationTask.TARGET_OPERATION,
+ inputs=inputs,
+ max_attempts=max_attempts,
+ retry_interval=retry_interval)
+
+ assert api_task.name == '{0}.{1}'.format(operation_name, relationship_instance.id)
+ assert api_task.operation_mapping is True
+ assert api_task.actor == relationship_instance
+ assert api_task.inputs == inputs
+ assert api_task.retry_interval == retry_interval
+ assert api_task.max_attempts == max_attempts
+ assert api_task.plugin == {'name': 'plugin',
+ 'package_name': 'package',
+ 'package_version': '0.1'}
def test_operation_task_default_values(self, ctx):
dependency_node_instance = ctx.model.node_instance.get_by_name(
@@ -106,6 +150,7 @@ class TestOperationTask(object):
assert task.retry_interval == ctx._task_retry_interval
assert task.max_attempts == ctx._task_max_attempts
assert task.ignore_failure == ctx._task_ignore_failure
+ assert task.plugin == {}
class TestWorkflowTask(object):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/orchestrator/workflows/core/test_task.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/core/test_task.py b/tests/orchestrator/workflows/core/test_task.py
index c572501..6c3825c 100644
--- a/tests/orchestrator/workflows/core/test_task.py
+++ b/tests/orchestrator/workflows/core/test_task.py
@@ -42,24 +42,30 @@ class TestOperationTask(object):
with workflow_context.current.push(ctx):
api_task = api.task.OperationTask.node_instance(
instance=node_instance,
- name='aria.interfaces.lifecycle.create',
- )
-
+ name='aria.interfaces.lifecycle.create')
core_task = core.task.OperationTask(api_task=api_task)
-
return api_task, core_task
def test_operation_task_creation(self, ctx):
+ storage_plugin = mock.models.get_plugin(package_name='p1', package_version='0.1')
+ storage_plugin_other = mock.models.get_plugin(package_name='p0', package_version='0.0')
+ ctx.model.plugin.put(storage_plugin_other)
+ ctx.model.plugin.put(storage_plugin)
node_instance = \
ctx.model.node_instance.get_by_name(mock.models.DEPENDENCY_NODE_INSTANCE_NAME)
+ node = node_instance.node
+ node.plugins = [{'name': 'plugin1',
+ 'package_name': 'p1',
+ 'package_version': '0.1'}]
+ node.operations['aria.interfaces.lifecycle.create'] = {'plugin': 'plugin1'}
api_task, core_task = self._create_operation_task(ctx, node_instance)
storage_task = ctx.model.task.get_by_name(core_task.name)
-
assert core_task.model_task == storage_task
assert core_task.name == api_task.name
assert core_task.operation_mapping == api_task.operation_mapping
assert core_task.actor == api_task.actor == node_instance
assert core_task.inputs == api_task.inputs == storage_task.inputs
+ assert core_task.plugin == storage_plugin
def test_operation_task_edit_locked_attribute(self, ctx):
node_instance = \
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/orchestrator/workflows/executor/test_executor.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/executor/test_executor.py b/tests/orchestrator/workflows/executor/test_executor.py
index 654542c..7a11524 100644
--- a/tests/orchestrator/workflows/executor/test_executor.py
+++ b/tests/orchestrator/workflows/executor/test_executor.py
@@ -14,6 +14,7 @@
# limitations under the License.
import logging
+import os
import uuid
from contextlib import contextmanager
@@ -28,57 +29,34 @@ except ImportError:
_celery = None
app = None
+import aria
from aria.storage import models
from aria.orchestrator import events
from aria.orchestrator.workflows.executor import (
thread,
- multiprocess,
- blocking,
+ process,
# celery
)
-class TestExecutor(object):
-
- @pytest.mark.parametrize('executor_cls,executor_kwargs', [
- (thread.ThreadExecutor, {'pool_size': 1}),
- (thread.ThreadExecutor, {'pool_size': 2}),
- (multiprocess.MultiprocessExecutor, {'pool_size': 1}),
- (multiprocess.MultiprocessExecutor, {'pool_size': 2}),
- (blocking.CurrentThreadBlockingExecutor, {}),
- # (celery.CeleryExecutor, {'app': app})
- ])
- def test_execute(self, executor_cls, executor_kwargs):
- self.executor = executor_cls(**executor_kwargs)
- expected_value = 'value'
- successful_task = MockTask(mock_successful_task)
- failing_task = MockTask(mock_failing_task)
- task_with_inputs = MockTask(mock_task_with_input, inputs={'input': expected_value})
-
- for task in [successful_task, failing_task, task_with_inputs]:
- self.executor.execute(task)
-
- @retrying.retry(stop_max_delay=10000, wait_fixed=100)
- def assertion():
- assert successful_task.states == ['start', 'success']
- assert failing_task.states == ['start', 'failure']
- assert task_with_inputs.states == ['start', 'failure']
- assert isinstance(failing_task.exception, MockException)
- assert isinstance(task_with_inputs.exception, MockException)
- assert task_with_inputs.exception.message == expected_value
- assertion()
-
- def setup_method(self):
- events.start_task_signal.connect(start_handler)
- events.on_success_task_signal.connect(success_handler)
- events.on_failure_task_signal.connect(failure_handler)
-
- def teardown_method(self):
- events.start_task_signal.disconnect(start_handler)
- events.on_success_task_signal.disconnect(success_handler)
- events.on_failure_task_signal.disconnect(failure_handler)
- if hasattr(self, 'executor'):
- self.executor.close()
+def test_execute(executor):
+ expected_value = 'value'
+ successful_task = MockTask(mock_successful_task)
+ failing_task = MockTask(mock_failing_task)
+ task_with_inputs = MockTask(mock_task_with_input, inputs={'input': expected_value})
+
+ for task in [successful_task, failing_task, task_with_inputs]:
+ executor.execute(task)
+
+ @retrying.retry(stop_max_delay=10000, wait_fixed=100)
+ def assertion():
+ assert successful_task.states == ['start', 'success']
+ assert failing_task.states == ['start', 'failure']
+ assert task_with_inputs.states == ['start', 'failure']
+ assert isinstance(failing_task.exception, MockException)
+ assert isinstance(task_with_inputs.exception, MockException)
+ assert task_with_inputs.exception.message == expected_value
+ assertion()
def mock_successful_task(**_):
@@ -116,9 +94,10 @@ class MockTask(object):
self.logger = logging.getLogger()
self.name = name
self.inputs = inputs or {}
- self.context = ctx or None
+ self.context = ctx
self.retry_count = 0
self.max_attempts = 1
+ self.plugin_id = None
for state in models.Task.STATES:
setattr(self, state.upper(), state)
@@ -128,14 +107,36 @@ class MockTask(object):
yield self
-def start_handler(task, *args, **kwargs):
- task.states.append('start')
-
-
-def success_handler(task, *args, **kwargs):
- task.states.append('success')
-
-
-def failure_handler(task, exception, *args, **kwargs):
- task.states.append('failure')
- task.exception = exception
+@pytest.fixture(params=[
+ (thread.ThreadExecutor, {'pool_size': 1}),
+ (thread.ThreadExecutor, {'pool_size': 2}),
+ # subprocess needs to load a tests module so we explicitly add the root directory as if
+ # the project has been installed in editable mode
+ (process.ProcessExecutor, {'python_path': [os.path.dirname(os.path.dirname(aria.__file__))]}),
+ # (celery.CeleryExecutor, {'app': app})
+])
+def executor(request):
+ executor_cls, executor_kwargs = request.param
+ result = executor_cls(**executor_kwargs)
+ yield result
+ result.close()
+
+
+@pytest.fixture(autouse=True)
+def register_signals():
+ def start_handler(task, *args, **kwargs):
+ task.states.append('start')
+
+ def success_handler(task, *args, **kwargs):
+ task.states.append('success')
+
+ def failure_handler(task, exception, *args, **kwargs):
+ task.states.append('failure')
+ task.exception = exception
+ events.start_task_signal.connect(start_handler)
+ events.on_success_task_signal.connect(success_handler)
+ events.on_failure_task_signal.connect(failure_handler)
+ yield
+ events.start_task_signal.disconnect(start_handler)
+ events.on_success_task_signal.disconnect(success_handler)
+ events.on_failure_task_signal.disconnect(failure_handler)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/orchestrator/workflows/executor/test_process_executor.py
----------------------------------------------------------------------
diff --git a/tests/orchestrator/workflows/executor/test_process_executor.py b/tests/orchestrator/workflows/executor/test_process_executor.py
new file mode 100644
index 0000000..364d354
--- /dev/null
+++ b/tests/orchestrator/workflows/executor/test_process_executor.py
@@ -0,0 +1,130 @@
+# 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.
+
+import logging
+import os
+import uuid
+import Queue
+from contextlib import contextmanager
+
+import pytest
+
+from aria import application_model_storage
+from aria.storage import models
+from aria.utils.plugin import create as create_plugin
+from aria.storage.sql_mapi import SQLAlchemyModelAPI
+from aria.orchestrator import events
+from aria.orchestrator import plugin
+from aria.orchestrator.workflows.executor import process
+
+
+import tests.storage
+import tests.resources
+
+
+class TestProcessExecutor(object):
+
+ def test_plugin_execution(self, executor, mock_plugin):
+ task = MockTask(plugin=mock_plugin,
+ operation='mock_plugin1.operation')
+
+ queue = Queue.Queue()
+
+ def handler(_, exception=None):
+ queue.put(exception)
+
+ events.on_success_task_signal.connect(handler)
+ events.on_failure_task_signal.connect(handler)
+ try:
+ executor.execute(task)
+ error = queue.get(timeout=60)
+ # tests/resources/plugins/mock-plugin1 is the plugin installed
+ # during this tests setup. The module mock_plugin1 contains a single
+ # operation named "operation" which calls an entry point defined in the plugin's
+ # setup.py. This entry points simply prints 'mock-plugin-output' to stdout.
+ # The "operation" operation that called this subprocess, then raises a RuntimeError
+ # with that subprocess output as the error message.
+ # This is what we assert here. This tests checks that both the PYTHONPATH (operation)
+ # and PATH (entry point) are properly updated in the subprocess in which the task is
+ # running.
+ assert isinstance(error, RuntimeError)
+ assert error.message == 'mock-plugin-output'
+ finally:
+ events.on_success_task_signal.disconnect(handler)
+ events.on_failure_task_signal.disconnect(handler)
+
+ def test_closed(self, executor):
+ executor.close()
+ with pytest.raises(RuntimeError) as exc_info:
+ executor.execute(task=None)
+ assert 'closed' in exc_info.value.message
+
+
+@pytest.fixture
+def model(tmpdir):
+ api_kwargs = tests.storage.get_sqlite_api_kwargs(str(tmpdir))
+ result = application_model_storage(SQLAlchemyModelAPI, api_kwargs=api_kwargs)
+ yield result
+ tests.storage.release_sqlite_storage(result)
+
+
+@pytest.fixture
+def plugins_dir(tmpdir):
+ result = tmpdir.join('plugins')
+ result.mkdir()
+ return str(result)
+
+
+@pytest.fixture
+def plugin_manager(model, plugins_dir):
+ return plugin.PluginManager(model=model, plugins_dir=plugins_dir)
+
+
+@pytest.fixture
+def executor(plugin_manager):
+ result = process.ProcessExecutor(plugin_manager=plugin_manager)
+ yield result
+ result.close()
+
+
+@pytest.fixture
+def mock_plugin(plugin_manager, tmpdir):
+ source = os.path.join(tests.resources.DIR, 'plugins', 'mock-plugin1')
+ plugin_path = create_plugin(source=source, destination_dir=str(tmpdir))
+ return plugin_manager.install(source=plugin_path)
+
+
+class MockTask(object):
+
+ INFINITE_RETRIES = models.Task.INFINITE_RETRIES
+
+ def __init__(self, plugin, operation):
+ self.id = str(uuid.uuid4())
+ self.operation_mapping = operation
+ self.logger = logging.getLogger()
+ self.name = operation
+ self.inputs = {}
+ self.context = None
+ self.retry_count = 0
+ self.max_attempts = 1
+ self.plugin_id = plugin.id
+ self.plugin = plugin
+
+ for state in models.Task.STATES:
+ setattr(self, state.upper(), state)
+
+ @contextmanager
+ def _update(self):
+ yield self
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/resources/__init__.py
----------------------------------------------------------------------
diff --git a/tests/resources/__init__.py b/tests/resources/__init__.py
new file mode 100644
index 0000000..3ed601f
--- /dev/null
+++ b/tests/resources/__init__.py
@@ -0,0 +1,19 @@
+# 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.
+
+import os
+
+
+DIR = os.path.dirname(__file__)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/resources/plugins/mock-plugin1/mock_plugin1.py
----------------------------------------------------------------------
diff --git a/tests/resources/plugins/mock-plugin1/mock_plugin1.py b/tests/resources/plugins/mock-plugin1/mock_plugin1.py
new file mode 100644
index 0000000..25a00d1
--- /dev/null
+++ b/tests/resources/plugins/mock-plugin1/mock_plugin1.py
@@ -0,0 +1,27 @@
+# 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.
+
+import subprocess
+
+
+def operation(**_):
+ process = subprocess.Popen(['mock-plugin1'], stdout=subprocess.PIPE)
+ output, _ = process.communicate()
+ assert not process.poll()
+ raise RuntimeError(output.strip())
+
+
+def console_script_entry_point():
+ print 'mock-plugin-output'
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/resources/plugins/mock-plugin1/setup.py
----------------------------------------------------------------------
diff --git a/tests/resources/plugins/mock-plugin1/setup.py b/tests/resources/plugins/mock-plugin1/setup.py
new file mode 100644
index 0000000..88d354d
--- /dev/null
+++ b/tests/resources/plugins/mock-plugin1/setup.py
@@ -0,0 +1,28 @@
+# 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 setuptools import setup
+
+
+setup(
+ name='mock-plugin1',
+ version='0.1',
+ py_modules=['mock_plugin1'],
+ entry_points={
+ 'console_scripts': [
+ 'mock-plugin1 = mock_plugin1:console_script_entry_point'
+ ]
+ }
+)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/storage/test_models.py
----------------------------------------------------------------------
diff --git a/tests/storage/test_models.py b/tests/storage/test_models.py
index 0ae5d1c..0651957 100644
--- a/tests/storage/test_models.py
+++ b/tests/storage/test_models.py
@@ -111,7 +111,9 @@ def _node_instances_storage():
def _execution_storage():
storage = _deployment_storage()
execution = mock.models.get_execution(storage.deployment.list()[0])
+ plugin = mock.models.get_plugin()
storage.execution.put(execution)
+ storage.plugin.put(plugin)
return storage
@@ -531,34 +533,31 @@ class TestNode(object):
@pytest.mark.parametrize(
'is_valid, name, deploy_number_of_instances, max_number_of_instances, '
'min_number_of_instances, number_of_instances, planned_number_of_instances, plugins, '
- 'plugins_to_install, properties, operations, type, type_hierarchy',
+ 'properties, operations, type, type_hierarchy',
[
- (False, m_cls, 1, 1, 1, 1, 1, {}, {}, {}, {}, 'type', []),
- (False, 'name', m_cls, 1, 1, 1, 1, {}, {}, {}, {}, 'type', []),
- (False, 'name', 1, m_cls, 1, 1, 1, {}, {}, {}, {}, 'type', []),
- (False, 'name', 1, 1, m_cls, 1, 1, {}, {}, {}, {}, 'type', []),
- (False, 'name', 1, 1, 1, m_cls, 1, {}, {}, {}, {}, 'type', []),
- (False, 'name', 1, 1, 1, 1, m_cls, {}, {}, {}, {}, 'type', []),
- (False, 'name', 1, 1, 1, 1, 1, m_cls, {}, {}, {}, 'type', []),
- (False, 'name', 1, 1, 1, 1, 1, {}, m_cls, {}, {}, 'type', []),
- (False, 'name', 1, 1, 1, 1, 1, {}, {}, m_cls, {}, 'type', []),
- (False, 'name', 1, 1, 1, 1, 1, {}, {}, {}, m_cls, 'type', []),
- (False, 'name', 1, 1, 1, 1, 1, {}, {}, {}, {}, m_cls, []),
- (False, 'name', 1, 1, 1, 1, 1, {}, {}, {}, {}, 'type', m_cls),
-
- (True, 'name', 1, 1, 1, 1, 1, {}, {}, {}, {}, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, None, {}, {}, {}, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, {}, None, {}, {}, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, {}, {}, None, {}, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, {}, {}, {}, None, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, {}, {}, {}, {}, 'type', []),
- (True, 'name', 1, 1, 1, 1, 1, {}, {}, {}, {}, 'type', None),
+ (False, m_cls, 1, 1, 1, 1, 1, [], {}, {}, 'type', []),
+ (False, 'name', m_cls, 1, 1, 1, 1, [], {}, {}, 'type', []),
+ (False, 'name', 1, m_cls, 1, 1, 1, [], {}, {}, 'type', []),
+ (False, 'name', 1, 1, m_cls, 1, 1, [], {}, {}, 'type', []),
+ (False, 'name', 1, 1, 1, m_cls, 1, [], {}, {}, 'type', []),
+ (False, 'name', 1, 1, 1, 1, m_cls, [], {}, {}, 'type', []),
+ (False, 'name', 1, 1, 1, 1, 1, m_cls, {}, {}, 'type', []),
+ (False, 'name', 1, 1, 1, 1, 1, [], m_cls, {}, 'type', []),
+ (False, 'name', 1, 1, 1, 1, 1, [], {}, m_cls, 'type', []),
+ (False, 'name', 1, 1, 1, 1, 1, [], {}, {}, m_cls, []),
+ (False, 'name', 1, 1, 1, 1, 1, [], {}, {}, 'type', m_cls),
+
+ (True, 'name', 1, 1, 1, 1, 1, [], {}, {}, 'type', []),
+ (True, 'name', 1, 1, 1, 1, 1, None, {}, {}, 'type', []),
+ (True, 'name', 1, 1, 1, 1, 1, [], None, {}, 'type', []),
+ (True, 'name', 1, 1, 1, 1, 1, [], {}, None, 'type', []),
+ (True, 'name', 1, 1, 1, 1, 1, [], {}, {}, 'type', None),
]
)
def test_node_model_creation(self, deployment_storage, is_valid, name,
deploy_number_of_instances, max_number_of_instances,
min_number_of_instances, number_of_instances,
- planned_number_of_instances, plugins, plugins_to_install,
+ planned_number_of_instances, plugins,
properties, operations, type, type_hierarchy):
node = _test_model(
is_valid=is_valid,
@@ -573,7 +572,6 @@ class TestNode(object):
number_of_instances=number_of_instances,
planned_number_of_instances=planned_number_of_instances,
plugins=plugins,
- plugins_to_install=plugins_to_install,
properties=properties,
operations=operations,
type=type,
@@ -713,58 +711,56 @@ class TestProviderContext(object):
class TestPlugin(object):
@pytest.mark.parametrize(
'is_valid, archive_name, distribution, distribution_release, '
- 'distribution_version, excluded_wheels, package_name, package_source, '
+ 'distribution_version, package_name, package_source, '
'package_version, supported_platform, supported_py_versions, uploaded_at, wheels',
[
- (False, m_cls, 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', m_cls, 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', m_cls, 'dis_ver', {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', m_cls, {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', m_cls, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, m_cls, 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', m_cls, 'pak_ver',
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src', m_cls,
- {}, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', m_cls, {}, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, m_cls, now, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, m_cls, {}),
- (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, now, m_cls),
-
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, now, {}),
- (True, 'arc_name', None, 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', None, 'dis_ver', {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', None, {}, 'pak_name', 'pak_src', 'pak_ver',
- {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', None, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', None, 'pak_ver',
- {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src', None,
- {}, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', None, {}, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, None, now, {}),
- (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', {}, 'pak_name', 'pak_src',
- 'pak_ver', {}, {}, now, {}),
+ (False, m_cls, 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', m_cls, 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', m_cls, 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', m_cls, 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', m_cls, 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', m_cls, 'pak_ver',
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', m_cls,
+ 'sup_pla', [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', m_cls, [], now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', m_cls, now, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', [], m_cls, []),
+ (False, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', [], now, m_cls),
+
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', [], now, []),
+ (True, 'arc_name', None, 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', None, 'dis_ver', 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', None, 'pak_name', 'pak_src', 'pak_ver',
+ 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', None, 'pak_ver',
+ 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src', None,
+ 'sup_pla', [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', None, [], now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', None, now, []),
+ (True, 'arc_name', 'dis_name', 'dis_rel', 'dis_ver', 'pak_name', 'pak_src',
+ 'pak_ver', 'sup_pla', [], now, []),
]
)
def test_plugin_model_creation(self, empty_storage, is_valid, archive_name, distribution,
- distribution_release, distribution_version, excluded_wheels,
+ distribution_release, distribution_version,
package_name, package_source, package_version,
supported_platform, supported_py_versions, uploaded_at, wheels):
_test_model(is_valid=is_valid,
@@ -776,7 +772,6 @@ class TestPlugin(object):
distribution=distribution,
distribution_release=distribution_release,
distribution_version=distribution_version,
- excluded_wheels=excluded_wheels,
package_name=package_name,
package_source=package_source,
package_version=package_version,
@@ -791,34 +786,36 @@ class TestTask(object):
@pytest.mark.parametrize(
'is_valid, status, due_at, started_at, ended_at, max_attempts, retry_count, '
- 'retry_interval, ignore_failure, name, operation_mapping, inputs',
+ 'retry_interval, ignore_failure, name, operation_mapping, inputs, plugin_id',
[
- (False, m_cls, now, now, now, 1, 1, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, m_cls, now, now, 1, 1, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, now, m_cls, now, 1, 1, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, now, now, m_cls, 1, 1, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, now, now, now, m_cls, 1, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, now, now, now, 1, m_cls, 1, True, 'name', 'map', {}),
- (False, Task.STARTED, now, now, now, 1, 1, m_cls, True, 'name', 'map', {}),
- (False, Task.STARTED, now, now, now, 1, 1, 1, True, m_cls, 'map', {}),
- (False, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', m_cls, {}),
- (False, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', m_cls),
-
- (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', {}),
- (True, Task.STARTED, None, now, now, 1, 1, 1, True, 'name', 'map', {}),
- (True, Task.STARTED, now, None, now, 1, 1, 1, True, 'name', 'map', {}),
- (True, Task.STARTED, now, now, None, 1, 1, 1, True, 'name', 'map', {}),
- (True, Task.STARTED, now, now, now, 1, None, 1, True, 'name', 'map', {}),
- (True, Task.STARTED, now, now, now, 1, 1, None, True, 'name', 'map', {}),
- (True, Task.STARTED, now, now, now, 1, 1, 1, None, 'name', 'map', {}),
- (True, Task.STARTED, now, now, now, 1, 1, 1, True, None, 'map', {}),
- (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', None, {}),
- (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', None),
+ (False, m_cls, now, now, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, m_cls, now, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, m_cls, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, now, m_cls, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, now, now, m_cls, 1, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, now, now, 1, m_cls, 1, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, now, now, 1, 1, m_cls, True, 'name', 'map', {}, '1'),
+ (False, Task.STARTED, now, now, now, 1, 1, 1, True, m_cls, 'map', {}, '1'),
+ (False, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', m_cls, {}, '1'),
+ (False, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', m_cls, '1'),
+ (False, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', {}, m_cls),
+
+ (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, None, now, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, None, now, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, now, None, 1, 1, 1, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, None, 1, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, None, True, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, 1, None, 'name', 'map', {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, 1, True, None, 'map', {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', None, {}, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', None, '1'),
+ (True, Task.STARTED, now, now, now, 1, 1, 1, True, 'name', 'map', {}, None),
]
)
def test_task_model_creation(self, execution_storage, is_valid, status, due_at, started_at,
ended_at, max_attempts, retry_count, retry_interval,
- ignore_failure, name, operation_mapping, inputs):
+ ignore_failure, name, operation_mapping, inputs, plugin_id):
task = _test_model(
is_valid=is_valid,
storage=execution_storage,
@@ -837,9 +834,12 @@ class TestTask(object):
name=name,
operation_mapping=operation_mapping,
inputs=inputs,
+ plugin_id=plugin_id,
))
if is_valid:
assert task.execution == execution_storage.execution.list()[0]
+ if task.plugin_id:
+ assert task.plugin == execution_storage.plugin.list()[0]
def test_task_max_attempts_validation(self):
def create_task(max_attempts):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/utils/__init__.py
----------------------------------------------------------------------
diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py
new file mode 100644
index 0000000..ae1e83e
--- /dev/null
+++ b/tests/utils/__init__.py
@@ -0,0 +1,14 @@
+# 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.
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/5cf84eeb/tests/utils/test_plugin.py
----------------------------------------------------------------------
diff --git a/tests/utils/test_plugin.py b/tests/utils/test_plugin.py
new file mode 100644
index 0000000..6f2dd92
--- /dev/null
+++ b/tests/utils/test_plugin.py
@@ -0,0 +1,77 @@
+# 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.
+
+import os
+
+import pytest
+
+from aria import application_model_storage
+from aria.orchestrator import exceptions
+from aria.orchestrator import plugin
+from aria.utils.plugin import create as create_plugin
+from aria.storage.sql_mapi import SQLAlchemyModelAPI
+
+from .. import storage
+
+
+PACKAGE_NAME = 'mock-plugin'
+PACKAGE_VERSION = '100'
+
+
+class TestPluginManager(object):
+
+ def test_install(self, plugin_manager, mock_plugin, model, plugins_dir):
+ plugin = plugin_manager.install(mock_plugin)
+ assert plugin.package_name == PACKAGE_NAME
+ assert plugin.package_version == PACKAGE_VERSION
+ assert plugin == model.plugin.get(plugin.id)
+ plugin_prefix = os.path.join(plugins_dir, '{0}-{1}'.format(PACKAGE_NAME, PACKAGE_VERSION))
+ assert os.path.isdir(plugin_prefix)
+ assert plugin_prefix == plugin_manager.get_plugin_prefix(plugin)
+
+ def test_install_already_exits(self, plugin_manager, mock_plugin):
+ plugin_manager.install(mock_plugin)
+ with pytest.raises(exceptions.PluginAlreadyExistsError):
+ plugin_manager.install(mock_plugin)
+
+
+@pytest.fixture
+def model():
+ api_kwargs = storage.get_sqlite_api_kwargs()
+ model = application_model_storage(SQLAlchemyModelAPI, api_kwargs=api_kwargs)
+ yield model
+ storage.release_sqlite_storage(model)
+
+
+@pytest.fixture
+def plugins_dir(tmpdir):
+ result = tmpdir.join('plugins')
+ result.mkdir()
+ return str(result)
+
+
+@pytest.fixture
+def plugin_manager(model, plugins_dir):
+ return plugin.PluginManager(model=model, plugins_dir=plugins_dir)
+
+
+@pytest.fixture
+def mock_plugin(tmpdir):
+ source_dir = tmpdir.join('mock_plugin')
+ source_dir.mkdir()
+ setup_py = source_dir.join('setup.py')
+ setup_py.write('from setuptools import setup; setup(name="{0}", version="{1}")'
+ .format(PACKAGE_NAME, PACKAGE_VERSION))
+ return create_plugin(source=str(source_dir), destination_dir=str(tmpdir))