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/11/30 13:57:48 UTC
[3/3] incubator-ariatosca git commit: lynting
lynting
Project: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/commit/c8f0fe26
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/tree/c8f0fe26
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/diff/c8f0fe26
Branch: refs/heads/SQLAlchemy-based-models
Commit: c8f0fe26dce03e7a693ab3e4ca837775f0ee498c
Parents: 1a81e51
Author: mxmrlv <mx...@gmail.com>
Authored: Wed Nov 30 15:57:37 2016 +0200
Committer: mxmrlv <mx...@gmail.com>
Committed: Wed Nov 30 15:57:37 2016 +0200
----------------------------------------------------------------------
aria/orchestrator/__init__.py | 4 +-
aria/orchestrator/context/exceptions.py | 4 +-
aria/orchestrator/context/toolbelt.py | 1 -
aria/orchestrator/context/workflow.py | 2 +-
aria/orchestrator/exceptions.py | 7 +-
aria/orchestrator/workflows/builtin/heal.py | 16 +-
aria/orchestrator/workflows/builtin/install.py | 5 +-
aria/storage/__init__.py | 9 +-
aria/storage/api.py | 118 ++++++
aria/storage/api_driver/__init__.py | 18 -
aria/storage/api_driver/filesystem.py | 235 ------------
aria/storage/api_driver/inmemory.py | 144 -------
aria/storage/api_driver/sql.py | 382 ------------------
aria/storage/filesystem_api.py | 44 +++
aria/storage/mapi/__init__.py | 20 +
aria/storage/mapi/filesystem.py | 120 ++++++
aria/storage/mapi/inmemory.py | 148 +++++++
aria/storage/mapi/sql.py | 383 +++++++++++++++++++
aria/storage/models.py | 349 +++++++++++------
aria/storage/rapi/__init__.py | 18 +
aria/storage/rapi/filesystem.py | 115 ++++++
aria/storage/structures.py | 45 ++-
aria/storage/testing.py | 19 -
tests/mock/context.py | 4 +-
tests/orchestrator/context/test_operation.py | 7 +-
tests/orchestrator/context/test_toolbelt.py | 17 +-
tests/orchestrator/context/test_workflow.py | 2 +-
tests/orchestrator/workflows/api/test_task.py | 3 +-
.../orchestrator/workflows/core/test_engine.py | 4 +-
tests/storage/__init__.py | 8 +-
tests/storage/test_model_storage.py | 74 +---
tests/storage/test_resource_storage.py | 12 +-
32 files changed, 1289 insertions(+), 1048 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/__init__.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/__init__.py b/aria/orchestrator/__init__.py
index a5aeec7..90d6442 100644
--- a/aria/orchestrator/__init__.py
+++ b/aria/orchestrator/__init__.py
@@ -12,7 +12,9 @@
# 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 orchestrator
+"""
from .decorators import workflow, operation
from . import (
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/context/exceptions.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/context/exceptions.py b/aria/orchestrator/context/exceptions.py
index 6704bbc..fe762e1 100644
--- a/aria/orchestrator/context/exceptions.py
+++ b/aria/orchestrator/context/exceptions.py
@@ -12,7 +12,9 @@
# 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.
-
+"""
+Context based exceptions
+"""
from ..exceptions import OrchestratorError
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/context/toolbelt.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/context/toolbelt.py b/aria/orchestrator/context/toolbelt.py
index 3923f39..ae0e1ff 100644
--- a/aria/orchestrator/context/toolbelt.py
+++ b/aria/orchestrator/context/toolbelt.py
@@ -38,7 +38,6 @@ class NodeToolBelt(object):
self._op_context.model.relationship_instance.iter(filters=filters):
yield relationship_instance.source_node_instance
-
@property
def host_ip(self):
"""
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/context/workflow.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/context/workflow.py b/aria/orchestrator/context/workflow.py
index df72fa0..8797271 100644
--- a/aria/orchestrator/context/workflow.py
+++ b/aria/orchestrator/context/workflow.py
@@ -86,7 +86,7 @@ class WorkflowContext(BaseContext):
class _CurrentContext(threading.local):
"""
- Provides thread-level context, which sugarcoats the task api_driver.
+ Provides thread-level context, which sugarcoats the task mapi.
"""
def __init__(self):
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/exceptions.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/exceptions.py b/aria/orchestrator/exceptions.py
index 75b37cf..1a48194 100644
--- a/aria/orchestrator/exceptions.py
+++ b/aria/orchestrator/exceptions.py
@@ -12,9 +12,14 @@
# 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.
-
+"""
+Orchestrator based exceptions
+"""
from aria.exceptions import AriaError
class OrchestratorError(AriaError):
+ """
+ Orchestrator based exception
+ """
pass
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/workflows/builtin/heal.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/builtin/heal.py b/aria/orchestrator/workflows/builtin/heal.py
index 5eb75db..650e664 100644
--- a/aria/orchestrator/workflows/builtin/heal.py
+++ b/aria/orchestrator/workflows/builtin/heal.py
@@ -85,8 +85,9 @@ def heal_uninstall(ctx, graph, failing_node_instances, targeted_node_instances):
for node_instance in failing_node_instances:
node_instance_sub_workflow = node_instance_sub_workflows[node_instance.id]
for relationship_instance in reversed(node_instance.relationship_instance_source):
- graph.add_dependency(node_instance_sub_workflows[relationship_instance.target_node_instance.id],
- node_instance_sub_workflow)
+ graph.add_dependency(
+ node_instance_sub_workflows[relationship_instance.target_node_instance.id],
+ node_instance_sub_workflow)
# Add operations for intact nodes depending on a node instance belonging to node_instances
for node_instance in targeted_node_instances:
@@ -94,7 +95,8 @@ def heal_uninstall(ctx, graph, failing_node_instances, targeted_node_instances):
for relationship_instance in reversed(node_instance.relationship_instance_source):
- target_node_instance = ctx.model.node_instance.get(relationship_instance.target_node_instance.id)
+ target_node_instance = \
+ ctx.model.node_instance.get(relationship_instance.target_node_instance.id)
target_node_instance_subgraph = node_instance_sub_workflows[target_node_instance.id]
graph.add_dependency(target_node_instance_subgraph, node_instance_sub_workflow)
@@ -136,8 +138,9 @@ def heal_install(ctx, graph, failing_node_instances, targeted_node_instances):
for node_instance in failing_node_instances:
node_instance_sub_workflow = node_instance_sub_workflows[node_instance.id]
if node_instance.relationship_instance_source:
- dependencies = [node_instance_sub_workflows[relationship_instance.target_node_instance.id]
- for relationship_instance in node_instance.relationship_instance_source]
+ dependencies = \
+ [node_instance_sub_workflows[relationship_instance.target_node_instance.id]
+ for relationship_instance in node_instance.relationship_instance_source]
graph.add_dependency(node_instance_sub_workflow, dependencies)
# Add operations for intact nodes depending on a node instance
@@ -146,7 +149,8 @@ def heal_install(ctx, graph, failing_node_instances, targeted_node_instances):
node_instance_sub_workflow = node_instance_sub_workflows[node_instance.id]
for relationship_instance in node_instance.relationship_instance_source:
- target_node_instance = ctx.model.node_instance.get(relationship_instance.target_node_instance.id)
+ target_node_instance = ctx.model.node_instance.get(
+ relationship_instance.target_node_instance.id)
target_node_instance_subworkflow = node_instance_sub_workflows[target_node_instance.id]
graph.add_dependency(node_instance_sub_workflow, target_node_instance_subworkflow)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/orchestrator/workflows/builtin/install.py
----------------------------------------------------------------------
diff --git a/aria/orchestrator/workflows/builtin/install.py b/aria/orchestrator/workflows/builtin/install.py
index 7291d52..634811f 100644
--- a/aria/orchestrator/workflows/builtin/install.py
+++ b/aria/orchestrator/workflows/builtin/install.py
@@ -48,6 +48,7 @@ def install(ctx, graph, node_instances=(), node_instance_sub_workflows=None):
for node_instance in node_instances:
node_instance_sub_workflow = node_instance_sub_workflows[node_instance.id]
if node_instance.relationship_instance_source:
- dependencies = [node_instance_sub_workflows[relationship_instance.target_node_instance.id]
- for relationship_instance in node_instance.relationship_instance_source]
+ dependencies = [
+ node_instance_sub_workflows[relationship_instance.target_node_instance.id]
+ for relationship_instance in node_instance.relationship_instance_source]
graph.add_dependency(node_instance_sub_workflow, dependencies)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/__init__.py
----------------------------------------------------------------------
diff --git a/aria/storage/__init__.py b/aria/storage/__init__.py
index bb695d4..e5b1343 100644
--- a/aria/storage/__init__.py
+++ b/aria/storage/__init__.py
@@ -20,14 +20,14 @@ Path: aria.storage
Storage package is a generic abstraction over different storage types.
We define this abstraction with the following components:
-1. storage: simple api_driver to use
-2. driver: implementation of the database client api_driver.
+1. storage: simple mapi to use
+2. driver: implementation of the database client mapi.
3. model: defines the structure of the table/document.
4. field: defines a field/item in the model.
API:
* application_storage_factory - function, default Aria storage factory.
- * Storage - class, simple storage api_driver.
+ * Storage - class, simple storage mapi.
* models - module, default Aria standard models.
* structures - module, default Aria structures - holds the base model,
and different fields types.
@@ -96,5 +96,6 @@ class ModelStorage(Storage):
self.registered[model_name].create()
self.logger.debug('setup {name} in storage {self!r}'.format(name=model_name, self=self))
else:
- self.logger.debug('{name} in already storage {self!r}'.format(name=model_name, self=self))
+ self.logger.debug('{name} in already storage {self!r}'.format(name=model_name,
+ self=self))
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/api.py
----------------------------------------------------------------------
diff --git a/aria/storage/api.py b/aria/storage/api.py
index c313459..3ca1d1b 100644
--- a/aria/storage/api.py
+++ b/aria/storage/api.py
@@ -12,17 +12,32 @@
# 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.
+"""
+General storage API
+"""
from contextlib import contextmanager
from . import exceptions
class StorageAPI(object):
+ """
+ General storage Base API
+ """
def create(self, **kwargs):
+ """
+ Create a storage API.
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract create method')
@contextmanager
def connect(self):
+ """
+ Established a connection and destroys it after use.
+ :return:
+ """
try:
self._establish_connection()
yield self
@@ -32,60 +47,163 @@ class StorageAPI(object):
self._destroy_connection()
def _establish_connection(self):
+ """
+ Establish a conenction. used in the 'connect' contextmanager.
+ :return:
+ """
pass
def _destroy_connection(self):
+ """
+ Destroy a connection. used in the 'connect' contextmanager.
+ :return:
+ """
pass
+ def __getattr__(self, item):
+ try:
+ return self.registered[item]
+ except KeyError:
+ return super(StorageAPI, self).__getattribute__(item)
+
class ModelAPI(StorageAPI):
+ """
+ A Base object for the model.
+ """
def __init__(self, model_cls, name=None, **kwargs):
+ """
+ Base model API
+
+ :param model_cls: the representing class of the model
+ :param str name: the name of the model
+ :param kwargs:
+ """
super(ModelAPI, self).__init__(**kwargs)
self._model_cls = model_cls
self._name = name or generate_lower_name(model_cls)
@property
def name(self):
+ """
+ The name of the class
+ :return: name of the class
+ """
return self._name
@property
def model_cls(self):
+ """
+ The class represting the model
+ :return:
+ """
return self._model_cls
def get(self, entry_id, **kwargs):
+ """
+ Get entry from storage.
+
+ :param entry_id:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract get method')
def store(self, entry, **kwargs):
+ """
+ Store entry in storage
+
+ :param entry:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract store method')
def delete(self, entry_id, **kwargs):
+ """
+ Delete entry from storage.
+
+ :param entry_id:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract delete method')
def __iter__(self):
return self.iter()
def iter(self, **kwargs):
+ """
+ Iter over the entries in storage.
+
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract iter method')
def update(self, entry, **kwargs):
+ """
+ Update entry in storage.
+
+ :param entry:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract update method')
class ResourceAPI(StorageAPI):
+ """
+ A Base object for the resource.
+ """
def __init__(self, name):
+ """
+ Base resource API
+ :param str name: the resource type
+ """
self._name = name
@property
def name(self):
+ """
+ The name of the resource
+ :return:
+ """
return self._name
def data(self, entry_id, path=None, **kwargs):
+ """
+ Get a bytesteam from the storagee.
+
+ :param entry_id:
+ :param path:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract data method')
def download(self, entry_id, destination, path=None, **kwargs):
+ """
+ Download a resource from the storage.
+
+ :param entry_id:
+ :param destination:
+ :param path:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract download method')
def upload(self, entry_id, source, path=None, **kwargs):
+ """
+ Upload a resource to the storage.
+
+ :param entry_id:
+ :param source:
+ :param path:
+ :param kwargs:
+ :return:
+ """
raise NotImplementedError('Subclass must implement abstract upload method')
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/api_driver/__init__.py
----------------------------------------------------------------------
diff --git a/aria/storage/api_driver/__init__.py b/aria/storage/api_driver/__init__.py
deleted file mode 100644
index 127426a..0000000
--- a/aria/storage/api_driver/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from .filesystem import FileSystemModelAPI, FileSystemResourceAPI
-from .inmemory import InMemoryModelAPI
-from .sql import SQLAlchemyModelAPI
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/api_driver/filesystem.py
----------------------------------------------------------------------
diff --git a/aria/storage/api_driver/filesystem.py b/aria/storage/api_driver/filesystem.py
deleted file mode 100644
index 6ea2222..0000000
--- a/aria/storage/api_driver/filesystem.py
+++ /dev/null
@@ -1,235 +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.
-import os
-import shutil
-from functools import partial
-from multiprocessing import RLock
-from distutils import dir_util
-
-import jsonpickle
-
-from .. import (
- api,
- StorageError
-)
-
-
-# TODO: fix docs
-
-
-class FileSystemAPI(api.StorageAPI):
- """
- Base class which handles storage on the file system.
- """
- def __init__(self, *args, **kwargs):
- super(FileSystemAPI, self).__init__(*args, **kwargs)
- self._lock = RLock()
-
- def _establish_connection(self):
- self._lock.acquire()
-
- def _destroy_connection(self):
- self._lock.release()
-
- def __getstate__(self):
- obj_dict = super(FileSystemAPI, self).__getstate__()
- del obj_dict['_lock']
- return obj_dict
-
- def __setstate__(self, obj_dict):
- super(FileSystemAPI, self).__setstate__(obj_dict)
- vars(self).update(_lock=RLock(), **obj_dict)
-
-
-class FileSystemModelAPI(api.ModelAPI, FileSystemAPI):
- """
- File system model storage.
- """
-
- def __init__(self, directory, **kwargs):
- """
- File system implementation for storage api.
- :param str directory: root dir for storage.
- """
- super(FileSystemModelAPI, self).__init__(**kwargs)
- self.directory = directory
- self.base_path = os.path.join(self.directory, self.name)
- self._join_path = partial(os.path.join, self.base_path)
-
- def __repr__(self):
- return '{cls.__name__}(directory={self.directory})'.format(
- cls=self.__class__, self=self)
-
- def create(self, **kwargs):
- """
- Create directory in storage by path.
- tries to create the root directory as well.
- :param str name: path of file in storage.
- """
- with self.connect():
- try:
- os.makedirs(self.directory)
- except (OSError, IOError):
- pass
- os.makedirs(self.base_path)
-
- def get(self, entry_id, **kwargs):
- """
- Getter from storage.
- :param str entry_id: id of the file to get from storage.
- :return: value of file from storage.
- :rtype: dict
- """
- with self.connect():
- with open(self._join_path(entry_id)) as file_obj:
- return jsonpickle.loads(file_obj.read())
-
- def store(self, entry, **kwargs):
- """
- Delete from storage.
- :param Model entry: name of directory in storage.
- """
- with self.connect():
- with open(self._join_path(entry.id), 'w') as file_obj:
- file_obj.write(jsonpickle.dumps(entry))
-
- def delete(self, entry_id, **kwargs):
- """
- Delete from storage.
- :param str name: name of directory in storage.
- :param str entry_id: id of the file to delete from storage.
- """
- with self.connect():
- os.remove(self._join_path(entry_id))
-
- def iter(self, filters=None, **kwargs):
- """
- Generator over the entries of directory in storage.
- :param dict filters: filters for query
- """
- filters = filters or {}
- with self.connect():
- for entry_id in os.listdir(self.base_path):
- value = self.get(entry_id=entry_id)
- for filter_name, filter_value in filters.items():
- if value.get(filter_name) != filter_value:
- break
- else:
- yield value
-
- def update(self, entry_id, **kwargs):
- """
- Updates and entry in storage.
-
- :param str name: name of table/document in storage.
- :param str entry_id: id of the document to get from storage.
- :param kwargs: the fields to update.
- :return:
- """
- with self.connect():
- entry = self.get(entry_id)
- for key, value in kwargs.items():
- setattr(entry, key, value)
- self.store(entry)
-
-
-class FileSystemResourceAPI(api.ResourceAPI, FileSystemAPI):
- """
- File system resource storage.
- """
-
- def __init__(self, directory, **kwargs):
- """
- File system implementation for storage api.
- :param str directory: root dir for storage.
- """
- super(FileSystemResourceAPI, self).__init__(**kwargs)
- self.directory = directory
- self.base_path = os.path.join(self.directory, self.name)
- self._join_path = partial(os.path.join, self.base_path)
-
- def __repr__(self):
- return '{cls.__name__}(directory={self.directory})'.format(
- cls=self.__class__, self=self)
-
- def create(self, **kwargs):
- """
- Create directory in storage by path.
- tries to create the root directory as well.
- :param str name: path of file in storage.
- """
- try:
- os.makedirs(self.directory)
- except (OSError, IOError):
- pass
- os.makedirs(self.base_path)
-
- def data(self, entry_id, path=None, **_):
- """
- Retrieve the content of a file system storage resource.
-
- :param str entry_type: the type of the entry.
- :param str entry_id: the id of the entry.
- :param str path: a path to a specific resource.
- :return: the content of the file
- :rtype: bytes
- """
- resource_relative_path = os.path.join(self.name, entry_id, path or '')
- resource = os.path.join(self.directory, resource_relative_path)
- if not os.path.exists(resource):
- raise StorageError("Resource {0} does not exist".format(resource_relative_path))
- if not os.path.isfile(resource):
- resources = os.listdir(resource)
- if len(resources) != 1:
- raise StorageError('No resource in path: {0}'.format(resource))
- resource = os.path.join(resource, resources[0])
- with open(resource, 'rb') as resource_file:
- return resource_file.read()
-
- def download(self, entry_id, destination, path=None, **_):
- """
- Download a specific file or dir from the file system resource storage.
-
- :param str entry_type: the name of the entry.
- :param str entry_id: the id of the entry
- :param str destination: the destination of the files.
- :param str path: a path on the remote machine relative to the root of the entry.
- """
- resource_relative_path = os.path.join(self.name, entry_id, path or '')
- resource = os.path.join(self.directory, resource_relative_path)
- if not os.path.exists(resource):
- raise StorageError("Resource {0} does not exist".format(resource_relative_path))
- if os.path.isfile(resource):
- shutil.copy2(resource, destination)
- else:
- dir_util.copy_tree(resource, destination) # pylint: disable=no-member
-
- def upload(self, entry_id, source, path=None, **_):
- """
- Uploads a specific file or dir to the file system resource storage.
-
- :param str entry_type: the name of the entry.
- :param str entry_id: the id of the entry
- :param source: the source of the files to upload.
- :param path: the destination of the file/s relative to the entry root dir.
- """
- resource_directory = os.path.join(self.directory, self.name, entry_id)
- if not os.path.exists(resource_directory):
- os.makedirs(resource_directory)
- destination = os.path.join(resource_directory, path or '')
- if os.path.isfile(source):
- shutil.copy2(source, destination)
- else:
- dir_util.copy_tree(source, destination) # pylint: disable=no-member
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/api_driver/inmemory.py
----------------------------------------------------------------------
diff --git a/aria/storage/api_driver/inmemory.py b/aria/storage/api_driver/inmemory.py
deleted file mode 100644
index fb27673..0000000
--- a/aria/storage/api_driver/inmemory.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from collections import namedtuple
-
-from aria.storage.structures import db
-
-from .. import api
-
-
-_Pointer = namedtuple('_Pointer', 'name, is_iter')
-
-storage = {}
-
-
-class InMemoryModelAPI(api.ModelAPI):
- def __init__(self, *args, **kwargs):
- """
- Managing the model in the storage, using the driver.
-
- :param basestring name: the name of the model.
- :param ModelDriver driver: the driver which supports this model in the storage.
- :param Model model_cls: table/document class model.
- """
- super(InMemoryModelAPI, self).__init__(*args, **kwargs)
- self.pointer_mapping = {}
-
- def create(self):
- """
- Creates the model in the storage.
- """
- with self.connect():
- storage[self.name] = {}
- self._setup_pointers_mapping()
-
- def _setup_pointers_mapping(self):
- for field_name, field_cls in vars(self.model_cls).items():
- if not (getattr(field_cls, 'impl', None) is not None and
- isinstance(field_cls.impl.parent_token, db.RelationshipProperty)):
- continue
- pointer_key = _Pointer(field_name, is_iter=False)
- self.pointer_mapping[pointer_key] = self.__class__(
- name=api.generate_lower_name(field_cls.class_),
- model_cls=field_cls.class_)
-
- def get(self, entry_id, **kwargs):
- """
- Getter for the model from the storage.
-
- :param basestring entry_id: the id of the table/document.
- :return: model instance
- :rtype: Model
- """
- with self.connect():
- data = storage[self.name][entry_id]
- data.update(self._get_pointers(data, **kwargs))
- return self.model_cls(**data)
-
- def store(self, entry, **kwargs):
- """
- Setter for the model in the storage.
-
- :param Model entry: the table/document to store.
- """
- with self.connect():
- data = entry.fields_dict
- data.update(self._store_pointers(data, **kwargs))
- storage[self.name][entry.id] = data
-
- def delete(self, entry_id, **kwargs):
- """
- Delete the model from storage.
-
- :param basestring entry_id: id of the entity to delete from storage.
- """
- entry = self.get(entry_id)
- with self.connect():
- self._delete_pointers(entry, **kwargs)
- storage[self.name].pop(entry_id)
-
- def iter(self, **kwargs):
- """
- Generator over the entries of model in storage.
- """
- with self.connect():
- for data in storage[self.name].values():
- data.update(self._get_pointers(data, **kwargs))
- yield self.model_cls(**data)
-
- def update(self, entry_id, **kwargs):
- """
- Updates and entry in storage.
-
- :param str entry_id: the id of the table/document.
- :param kwargs: the fields to update.
- :return:
- """
- with self.connect():
- storage[self.name][entry_id].update(**kwargs)
-
- def _get_pointers(self, data, **kwargs):
- pointers = {}
- for field, schema in self.pointer_mapping.items():
- if field.is_iter:
- pointers[field.name] = [
- schema.get(entry_id=pointer_id, **kwargs)
- for pointer_id in data[field.name]
- if pointer_id]
- elif data[field.name]:
- pointers[field.name] = schema.get(entry_id=data[field.name], **kwargs)
- return pointers
-
- def _store_pointers(self, data, **kwargs):
- pointers = {}
- for field, model_api in self.pointer_mapping.items():
- if field.is_iter:
- pointers[field.name] = []
- for iter_entity in data[field.name]:
- pointers[field.name].append(iter_entity.id)
- model_api.store(iter_entity, **kwargs)
- else:
- pointers[field.name] = data[field.name].id
- model_api.store(data[field.name], **kwargs)
- return pointers
-
- def _delete_pointers(self, entry, **kwargs):
- for field, schema in self.pointer_mapping.items():
- if field.is_iter:
- for iter_entry in getattr(entry, field.name):
- schema.delete(iter_entry.id, **kwargs)
- else:
- schema.delete(getattr(entry, field.name).id, **kwargs)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/api_driver/sql.py
----------------------------------------------------------------------
diff --git a/aria/storage/api_driver/sql.py b/aria/storage/api_driver/sql.py
deleted file mode 100644
index 6f5a10a..0000000
--- a/aria/storage/api_driver/sql.py
+++ /dev/null
@@ -1,382 +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.
-import copy
-from collections import OrderedDict
-
-from sqlite3 import DatabaseError as SQLiteDBError
-from sqlalchemy.exc import SQLAlchemyError
-from sqlalchemy.sql.elements import Label
-
-try:
- from psycopg2 import DatabaseError as Psycopg2DBError
- sql_errors = (SQLAlchemyError, SQLiteDBError, Psycopg2DBError)
-except ImportError:
- sql_errors = (SQLAlchemyError, SQLiteDBError)
- Psycopg2DBError = None
-
-from ... import storage
-
-
-DEFAULT_SQL_DIALECT = 'sqlite'
-
-
-class SQLAlchemyModelAPI(storage.api.ModelAPI):
-
- def __init__(self,
- app,
- sql_dialect=DEFAULT_SQL_DIALECT,
- username='',
- password='',
- host='localhost',
- db_name='',
- **kwargs):
- super(SQLAlchemyModelAPI, self).__init__(**kwargs)
- self._app = app
- self._sql_dialect = sql_dialect
- self._username = username
- self._password = password
- self._host = host
- self._db_name = db_name
-
- def get(self, entry_id, include=None, filters=None, locking=False):
- """Return a single result based on the model class and element ID
- """
- filters = filters or {'id': entry_id}
- query = self._get_query(include, filters)
- if locking:
- query = query.with_for_update()
- result = query.first()
-
- if not result:
- raise storage.exceptions.StorageError(
- 'Requested {0} with ID `{1}` was not found'
- .format(self.model_cls.__name__, entry_id)
- )
- return result
-
- def iter(self,
- include=None,
- filters=None,
- pagination=None,
- sort=None):
- """Return a (possibly empty) list of `model_class` results
- """
- query = self._get_query(include, filters, sort)
-
- results, _, _, _ = self._paginate(query, pagination)
-
- for result in results:
- yield result
-
- def store(self, entry, **kwargs):
- """Create a `model_class` instance from a serializable `model` object
-
- :param entry: A dict with relevant kwargs, or an instance of a class
- that has a `to_dict` method, and whose attributes match the columns
- of `model_class` (might also my just an instance of `model_class`)
- :return: An instance of `model_class`
- """
- storage.db.session.add(entry)
- self._safe_commit()
- return entry
-
- def delete(self, entry_id, filters=None):
- """Delete a single result based on the model class and element ID
- """
- try:
- instance = self.get(
- entry_id,
- filters=filters
- )
- except storage.exceptions.StorageError:
- raise storage.exceptions.StorageError(
- 'Could not delete {0} with ID `{1}` - element not found'
- .format(
- self.model_cls.__name__,
- entry_id
- )
- )
- self._load_properties(instance)
- storage.db.session.delete(instance)
- self._safe_commit()
- return instance
-
- # TODO: this might need rework
- def update(self, entry, **kwargs):
- """Add `instance` to the DB session, and attempt to commit
-
- :return: The updated instance
- """
- return self.store(entry)
-
- def refresh(self, entry):
- """Reload the instance with fresh information from the DB
-
- :param entry: Instance to be re-loaded from the DB
- :return: The refreshed instance
- """
- storage.db.session.refresh(entry)
- self._load_properties(entry)
- return entry
-
- def _destroy_connection(self):
- pass
-
- def _establish_connection(self):
- pass
-
- def create(self):
- if self._app.config.get('SQLALCHEMY_DATABASE_URI', None) is None:
- sql_uri_template = '{sql_dialect}://'
- if self._sql_dialect != DEFAULT_SQL_DIALECT:
- sql_uri_template = sql_uri_template + '{username}:{password}@{hostname}/{db_name}'
- self._app.config['SQLALCHEMY_DATABASE_URI'] = sql_uri_template.format(
- sql_dialect=self._sql_dialect,
- username=self._username,
- password=self._password,
- hostname=self._host,
- db_name=self._db_name)
-
- with self._app.app_context():
- if storage.structures.db.app is None:
- storage.structures.db.app = self._app
- storage.structures.db.init_app(self._app)
- self.model_cls.__table__.create(storage.structures.db.session.bind)
-
-
- @staticmethod
- def _safe_commit():
- """Try to commit changes in the session. Roll back if exception raised
- Excepts SQLAlchemy errors and rollbacks if they're caught
- """
- try:
- storage.db.session.commit()
- except sql_errors as e:
- storage.db.session.rollback()
- raise storage.exceptions.StorageError(
- 'SQL Storage error: {0}'.format(str(e))
- )
-
- def _get_base_query(self, include, joins):
- """Create the initial query from the model class and included columns
-
- :param include: A (possibly empty) list of columns to include in
- the query
- :param joins: A (possibly empty) list of models on which the query
- should join
- :return: An SQLAlchemy AppenderQuery object
- """
-
- # If only some columns are included, query through the session object
- if include:
- query = storage.db.session.query(*include)
- else:
- # If all columns should be returned, query directly from the model
- query = self.model_cls.query
-
- # Add any joins that might be necessary
- for join_model in joins:
- query = query.join(join_model)
-
- return query
-
- @staticmethod
- def _sort_query(query, sort=None):
- """Add sorting clauses to the query
-
- :param query: Base SQL query
- :param sort: An optional dictionary where keys are column names to
- sort by, and values are the order (asc/desc)
- :return: An SQLAlchemy AppenderQuery object
- """
- if sort:
- for column, order in sort.items():
- if order == 'desc':
- column = column.desc()
- query = query.order_by(column)
- return query
-
- @staticmethod
- def _filter_query(query, filters):
- """Add filter clauses to the query
-
- :param query: Base SQL query
- :param filters: An optional dictionary where keys are column names to
- filter by, and values are values applicable for those columns (or lists
- of such values)
- :return: An SQLAlchemy AppenderQuery object
- """
- for column, value in filters.items():
- # If there are multiple values, use `in_`, otherwise, use `eq`
- if isinstance(value, (list, tuple)):
- query = query.filter(column.in_(value))
- else:
- query = query.filter(column == value)
-
- return query
-
- def _get_query(self,
- include=None,
- filters=None,
- sort=None):
- """Get an SQL query object based on the params passed
-
- :param include: An optional list of columns to include in the query
- :param filters: An optional dictionary where keys are column names to
- filter by, and values are values applicable for those columns (or lists
- of such values)
- :param sort: An optional dictionary where keys are column names to
- sort by, and values are the order (asc/desc)
- :return: A sorted and filtered query with only the relevant
- columns
- """
-
- include = include or []
- filters = filters or dict()
- sort = sort or OrderedDict()
-
- joins = self._get_join_models_list(include, filters, sort)
- include, filters, sort = self._get_columns_from_field_names(
- include, filters, sort
- )
-
- query = self._get_base_query(include, joins)
- query = self._filter_query(query, filters)
- query = self._sort_query(query, sort)
- return query
-
- def _get_columns_from_field_names(self,
- include,
- filters,
- sort):
- """Go over the optional parameters (include, filters, sort), and
- replace column names with actual SQLA column objects
- """
- all_includes = [self._get_column(c) for c in include]
- include = []
- # Columns that are inferred from properties (Labels) should be included
- # last for the following joins to work properly
- for col in all_includes:
- if isinstance(col, Label):
- include.append(col)
- else:
- include.insert(0, col)
-
- filters = {self._get_column(c): filters[c] for c in filters}
- sort = OrderedDict((self._get_column(c), sort[c]) for c in sort)
-
- return include, filters, sort
-
- def _get_join_models_list(self, include, filters, sort):
- """Return a list of models on which the query should be joined, as
- inferred from the include, filter and sort column names
- """
- if not self.model_cls.is_resource:
- return []
-
- all_column_names = include + filters.keys() + sort.keys()
- join_columns = {column_name for column_name in all_column_names
- if self._is_join_column(column_name)}
-
- # If the only columns included are the columns on which we would
- # normally join, there isn't actually a need to join, as the FROM
- # clause in the query will be generated from the relevant models anyway
- if include == list(join_columns):
- return []
-
- # Initializing a set, because the same model can appear in several
- # join lists
- join_models = set()
- for column_name in join_columns:
- join_models.update(
- self.model_cls.join_properties[column_name]['models']
- )
- # Sort the models by their correct join order
- join_models = sorted(join_models,
- key=lambda model: model.join_order, reverse=True)
-
- return join_models
-
- def _is_join_column(self, column_name):
- """Return False if the column name corresponds to a regular SQLA
- column that `model_class` has.
- Return True if the column that should be used is a join column (see
- SQLModelBase for an explanation)
- """
- return self.model_cls.is_resource and \
- column_name in self.model_cls.join_properties
-
- def _get_column(self, column_name):
- """Return the column on which an action (filtering, sorting, etc.)
- would need to be performed. Can be either an attribute of the class,
- or needs to be inferred from the class' `join_properties` property
- """
- if self._is_join_column(column_name):
- return self.model_cls.join_properties[column_name]['column']
- else:
- return getattr(self.model_cls, column_name)
-
- # TODO is this really needed in aria?
- @staticmethod
- def _paginate(query, pagination):
- """Paginate the query by size and offset
-
- :param query: Current SQLAlchemy query object
- :param pagination: An optional dict with size and offset keys
- :return: A tuple with four elements:
- - results: `size` items starting from `offset`
- - the total count of items
- - `size` [default: 0]
- - `offset` [default: 0]
- """
- if pagination:
- size = pagination.get('size', 0)
- offset = pagination.get('offset', 0)
- total = query.order_by(None).count() # Fastest way to count
- results = query.limit(size).offset(offset).all()
- return results, total, size, offset
- else:
- results = query.all()
- return results, len(results), 0, 0
-
- @staticmethod
- def _load_properties(instance):
- """A helper method used to overcome a problem where the properties
- that rely on joins aren't being loaded automatically
- """
- if instance.is_resource:
- for prop in instance.join_properties:
- getattr(instance, prop)
-
- def clear(self):
- storage.db.session.query(self.name).delete()
- storage.db.session.commit()
-
-class ListResult(object):
- """
- a ListResult contains results about the requested items.
- """
- def __init__(self, items, metadata):
- self.items = items
- self.metadata = metadata
-
- def __len__(self):
- return len(self.items)
-
- def __iter__(self):
- return iter(self.items)
-
- def __getitem__(self, item):
- return self.items[item]
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/filesystem_api.py
----------------------------------------------------------------------
diff --git a/aria/storage/filesystem_api.py b/aria/storage/filesystem_api.py
new file mode 100644
index 0000000..03800ff
--- /dev/null
+++ b/aria/storage/filesystem_api.py
@@ -0,0 +1,44 @@
+# 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.
+"""
+Filesystem based API Base
+"""
+from multiprocessing import RLock
+
+from . import api
+
+
+class FileSystemAPI(api.StorageAPI):
+ """
+ Base class which handles storage on the file system.
+ """
+ def __init__(self, *args, **kwargs):
+ super(FileSystemAPI, self).__init__(*args, **kwargs)
+ self._lock = RLock()
+
+ def _establish_connection(self):
+ self._lock.acquire()
+
+ def _destroy_connection(self):
+ self._lock.release()
+
+ def __getstate__(self):
+ obj_dict = super(FileSystemAPI, self).__getstate__()
+ del obj_dict['_lock']
+ return obj_dict
+
+ def __setstate__(self, obj_dict):
+ super(FileSystemAPI, self).__setstate__(obj_dict)
+ vars(self).update(_lock=RLock(), **obj_dict)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/mapi/__init__.py
----------------------------------------------------------------------
diff --git a/aria/storage/mapi/__init__.py b/aria/storage/mapi/__init__.py
new file mode 100644
index 0000000..d4a8c6e
--- /dev/null
+++ b/aria/storage/mapi/__init__.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.
+"""
+A collection of MAPIs
+"""
+from .filesystem import FileSystemModelAPI
+from .inmemory import InMemoryModelAPI
+from .sql import SQLAlchemyModelAPI
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/mapi/filesystem.py
----------------------------------------------------------------------
diff --git a/aria/storage/mapi/filesystem.py b/aria/storage/mapi/filesystem.py
new file mode 100644
index 0000000..2a091d7
--- /dev/null
+++ b/aria/storage/mapi/filesystem.py
@@ -0,0 +1,120 @@
+# 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.
+"""
+SQLalchemy based MAPI
+"""
+import os
+from functools import partial
+
+import jsonpickle
+
+from .. import (
+ api,
+ filesystem_api
+)
+
+
+# TODO: fix docs
+
+class FileSystemModelAPI(api.ModelAPI, filesystem_api.FileSystemAPI):
+ """
+ File system model storage.
+ """
+
+ def __init__(self, directory, **kwargs):
+ """
+ File system implementation for storage api.
+ :param str directory: root dir for storage.
+ """
+ super(FileSystemModelAPI, self).__init__(**kwargs)
+ self.directory = directory
+ self.base_path = os.path.join(self.directory, self.name)
+ self._join_path = partial(os.path.join, self.base_path)
+
+ def __repr__(self):
+ return '{cls.__name__}(directory={self.directory})'.format(
+ cls=self.__class__, self=self)
+
+ def create(self, **kwargs):
+ """
+ Create directory in storage by path.
+ tries to create the root directory as well.
+ :param str name: path of file in storage.
+ """
+ with self.connect():
+ try:
+ os.makedirs(self.directory)
+ except (OSError, IOError):
+ pass
+ os.makedirs(self.base_path)
+
+ def get(self, entry_id, **kwargs):
+ """
+ Getter from storage.
+ :param str entry_id: id of the file to get from storage.
+ :return: value of file from storage.
+ :rtype: dict
+ """
+ with self.connect():
+ with open(self._join_path(entry_id)) as file_obj:
+ return jsonpickle.loads(file_obj.read())
+
+ def store(self, entry, **kwargs):
+ """
+ Delete from storage.
+ :param Model entry: name of directory in storage.
+ """
+ with self.connect():
+ with open(self._join_path(entry.id), 'w') as file_obj:
+ file_obj.write(jsonpickle.dumps(entry))
+
+ def delete(self, entry_id, **kwargs):
+ """
+ Delete from storage.
+ :param str name: name of directory in storage.
+ :param str entry_id: id of the file to delete from storage.
+ """
+ with self.connect():
+ os.remove(self._join_path(entry_id))
+
+ def iter(self, filters=None, **kwargs):
+ """
+ Generator over the entries of directory in storage.
+ :param dict filters: filters for query
+ """
+ filters = filters or {}
+ with self.connect():
+ for entry_id in os.listdir(self.base_path):
+ value = self.get(entry_id=entry_id)
+ for filter_name, filter_value in filters.items():
+ if value.get(filter_name) != filter_value:
+ break
+ else:
+ yield value
+
+ def update(self, entry_id, **kwargs):
+ """
+ Updates and entry in storage.
+
+ :param str name: name of table/document in storage.
+ :param str entry_id: id of the document to get from storage.
+ :param kwargs: the fields to update.
+ :return:
+ """
+ with self.connect():
+ entry = self.get(entry_id)
+ for key, value in kwargs.items():
+ setattr(entry, key, value)
+ self.store(entry)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/mapi/inmemory.py
----------------------------------------------------------------------
diff --git a/aria/storage/mapi/inmemory.py b/aria/storage/mapi/inmemory.py
new file mode 100644
index 0000000..10c730a
--- /dev/null
+++ b/aria/storage/mapi/inmemory.py
@@ -0,0 +1,148 @@
+# 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.
+
+
+# DEPRECATED
+# NOQA
+
+from collections import namedtuple
+
+from aria.storage.structures import db
+
+from .. import api
+
+
+_Pointer = namedtuple('_Pointer', 'name, is_iter')
+
+storage = {}
+
+
+class InMemoryModelAPI(api.ModelAPI):
+ def __init__(self, *args, **kwargs):
+ """
+ Managing the model in the storage, using the driver.
+
+ :param basestring name: the name of the model.
+ :param ModelDriver driver: the driver which supports this model in the storage.
+ :param Model model_cls: table/document class model.
+ """
+ super(InMemoryModelAPI, self).__init__(*args, **kwargs)
+ self.pointer_mapping = {}
+
+ def create(self):
+ """
+ Creates the model in the storage.
+ """
+ with self.connect():
+ storage[self.name] = {}
+ self._setup_pointers_mapping()
+
+ def _setup_pointers_mapping(self):
+ for field_name, field_cls in vars(self.model_cls).items():
+ if not (getattr(field_cls, 'impl', None) is not None and
+ isinstance(field_cls.impl.parent_token, db.RelationshipProperty)):
+ continue
+ pointer_key = _Pointer(field_name, is_iter=False)
+ self.pointer_mapping[pointer_key] = self.__class__(
+ name=api.generate_lower_name(field_cls.class_),
+ model_cls=field_cls.class_)
+
+ def get(self, entry_id, **kwargs):
+ """
+ Getter for the model from the storage.
+
+ :param basestring entry_id: the id of the table/document.
+ :return: model instance
+ :rtype: Model
+ """
+ with self.connect():
+ data = storage[self.name][entry_id]
+ data.update(self._get_pointers(data, **kwargs))
+ return self.model_cls(**data)
+
+ def store(self, entry, **kwargs):
+ """
+ Setter for the model in the storage.
+
+ :param Model entry: the table/document to store.
+ """
+ with self.connect():
+ data = entry.to_dict
+ data.update(self._store_pointers(data, **kwargs))
+ storage[self.name][entry.id] = data
+
+ def delete(self, entry_id, **kwargs):
+ """
+ Delete the model from storage.
+
+ :param basestring entry_id: id of the entity to delete from storage.
+ """
+ entry = self.get(entry_id)
+ with self.connect():
+ self._delete_pointers(entry, **kwargs)
+ storage[self.name].pop(entry_id)
+
+ def iter(self, **kwargs):
+ """
+ Generator over the entries of model in storage.
+ """
+ with self.connect():
+ for data in storage[self.name].values():
+ data.update(self._get_pointers(data, **kwargs))
+ yield self.model_cls(**data)
+
+ def update(self, entry_id, **kwargs):
+ """
+ Updates and entry in storage.
+
+ :param str entry_id: the id of the table/document.
+ :param kwargs: the fields to update.
+ :return:
+ """
+ with self.connect():
+ storage[self.name][entry_id].update(**kwargs)
+
+ def _get_pointers(self, data, **kwargs):
+ pointers = {}
+ for field, schema in self.pointer_mapping.items():
+ if field.is_iter:
+ pointers[field.name] = [
+ schema.get(entry_id=pointer_id, **kwargs)
+ for pointer_id in data[field.name]
+ if pointer_id]
+ elif data[field.name]:
+ pointers[field.name] = schema.get(entry_id=data[field.name], **kwargs)
+ return pointers
+
+ def _store_pointers(self, data, **kwargs):
+ pointers = {}
+ for field, model_api in self.pointer_mapping.items():
+ if field.is_iter:
+ pointers[field.name] = []
+ for iter_entity in data[field.name]:
+ pointers[field.name].append(iter_entity.id)
+ model_api.store(iter_entity, **kwargs)
+ else:
+ pointers[field.name] = data[field.name].id
+ model_api.store(data[field.name], **kwargs)
+ return pointers
+
+ def _delete_pointers(self, entry, **kwargs):
+ for field, schema in self.pointer_mapping.items():
+ if field.is_iter:
+ for iter_entry in getattr(entry, field.name):
+ schema.delete(iter_entry.id, **kwargs)
+ else:
+ schema.delete(getattr(entry, field.name).id, **kwargs)
http://git-wip-us.apache.org/repos/asf/incubator-ariatosca/blob/c8f0fe26/aria/storage/mapi/sql.py
----------------------------------------------------------------------
diff --git a/aria/storage/mapi/sql.py b/aria/storage/mapi/sql.py
new file mode 100644
index 0000000..57f143d
--- /dev/null
+++ b/aria/storage/mapi/sql.py
@@ -0,0 +1,383 @@
+# 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.
+"""
+SQLalchemy based MAPI
+"""
+from collections import OrderedDict
+
+from sqlite3 import DatabaseError as SQLiteDBError
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.sql.elements import Label
+
+try:
+ from psycopg2 import DatabaseError as Psycopg2DBError
+ sql_errors = (SQLAlchemyError, SQLiteDBError, Psycopg2DBError)
+except ImportError:
+ sql_errors = (SQLAlchemyError, SQLiteDBError)
+ Psycopg2DBError = None
+
+from ... import storage
+
+
+DEFAULT_SQL_DIALECT = 'sqlite'
+
+
+class SQLAlchemyModelAPI(storage.api.ModelAPI):
+ """
+ SQL based MAPI.
+ """
+ def __init__(self,
+ app,
+ sql_dialect=DEFAULT_SQL_DIALECT,
+ username='',
+ password='',
+ host='localhost',
+ db_name='',
+ **kwargs):
+ super(SQLAlchemyModelAPI, self).__init__(**kwargs)
+ self._app = app
+ self._sql_dialect = sql_dialect
+ self._username = username
+ self._password = password
+ self._host = host
+ self._db_name = db_name
+
+ def get(self, entry_id, include=None, filters=None, locking=False):
+ """Return a single result based on the model class and element ID
+ """
+ filters = filters or {'id': entry_id}
+ query = self._get_query(include, filters)
+ if locking:
+ query = query.with_for_update()
+ result = query.first()
+
+ if not result:
+ raise storage.exceptions.StorageError(
+ 'Requested {0} with ID `{1}` was not found'
+ .format(self.model_cls.__name__, entry_id)
+ )
+ return result
+
+ def iter(self,
+ include=None,
+ filters=None,
+ pagination=None,
+ sort=None):
+ """Return a (possibly empty) list of `model_class` results
+ """
+ query = self._get_query(include, filters, sort)
+
+ results, _, _, _ = self._paginate(query, pagination)
+
+ for result in results:
+ yield result
+
+ def store(self, entry, **kwargs):
+ """Create a `model_class` instance from a serializable `model` object
+
+ :param entry: A dict with relevant kwargs, or an instance of a class
+ that has a `to_dict` method, and whose attributes match the columns
+ of `model_class` (might also my just an instance of `model_class`)
+ :return: An instance of `model_class`
+ """
+ storage.db.session.add(entry)
+ self._safe_commit()
+ return entry
+
+ def delete(self, entry_id, filters=None):
+ """Delete a single result based on the model class and element ID
+ """
+ try:
+ instance = self.get(
+ entry_id,
+ filters=filters
+ )
+ except storage.exceptions.StorageError:
+ raise storage.exceptions.StorageError(
+ 'Could not delete {0} with ID `{1}` - element not found'
+ .format(
+ self.model_cls.__name__,
+ entry_id
+ )
+ )
+ self._load_properties(instance)
+ storage.db.session.delete(instance)
+ self._safe_commit()
+ return instance
+
+ # TODO: this might need rework
+ def update(self, entry, **kwargs):
+ """Add `instance` to the DB session, and attempt to commit
+
+ :return: The updated instance
+ """
+ return self.store(entry)
+
+ def refresh(self, entry):
+ """Reload the instance with fresh information from the DB
+
+ :param entry: Instance to be re-loaded from the DB
+ :return: The refreshed instance
+ """
+ storage.db.session.refresh(entry)
+ self._load_properties(entry)
+ return entry
+
+ def _destroy_connection(self):
+ pass
+
+ def _establish_connection(self):
+ pass
+
+ def create(self):
+ if self._app.config.get('SQLALCHEMY_DATABASE_URI', None) is None:
+ sql_uri_template = '{sql_dialect}://'
+ if self._sql_dialect != DEFAULT_SQL_DIALECT:
+ sql_uri_template = sql_uri_template + '{username}:{password}@{hostname}/{db_name}'
+ self._app.config['SQLALCHEMY_DATABASE_URI'] = sql_uri_template.format(
+ sql_dialect=self._sql_dialect,
+ username=self._username,
+ password=self._password,
+ hostname=self._host,
+ db_name=self._db_name)
+
+ with self._app.app_context():
+ if storage.structures.db.app is None:
+ storage.structures.db.app = self._app
+ storage.structures.db.init_app(self._app)
+ self.model_cls.__table__.create(storage.structures.db.session.bind)
+
+
+ @staticmethod
+ def _safe_commit():
+ """Try to commit changes in the session. Roll back if exception raised
+ Excepts SQLAlchemy errors and rollbacks if they're caught
+ """
+ try:
+ storage.db.session.commit()
+ except sql_errors as e:
+ storage.db.session.rollback()
+ raise storage.exceptions.StorageError(
+ 'SQL Storage error: {0}'.format(str(e))
+ )
+
+ def _get_base_query(self, include, joins):
+ """Create the initial query from the model class and included columns
+
+ :param include: A (possibly empty) list of columns to include in
+ the query
+ :param joins: A (possibly empty) list of models on which the query
+ should join
+ :return: An SQLAlchemy AppenderQuery object
+ """
+
+ # If only some columns are included, query through the session object
+ if include:
+ query = storage.db.session.query(*include)
+ else:
+ # If all columns should be returned, query directly from the model
+ query = self.model_cls.query
+
+ # Add any joins that might be necessary
+ for join_model in joins:
+ query = query.join(join_model)
+
+ return query
+
+ @staticmethod
+ def _sort_query(query, sort=None):
+ """Add sorting clauses to the query
+
+ :param query: Base SQL query
+ :param sort: An optional dictionary where keys are column names to
+ sort by, and values are the order (asc/desc)
+ :return: An SQLAlchemy AppenderQuery object
+ """
+ if sort:
+ for column, order in sort.items():
+ if order == 'desc':
+ column = column.desc()
+ query = query.order_by(column)
+ return query
+
+ @staticmethod
+ def _filter_query(query, filters):
+ """Add filter clauses to the query
+
+ :param query: Base SQL query
+ :param filters: An optional dictionary where keys are column names to
+ filter by, and values are values applicable for those columns (or lists
+ of such values)
+ :return: An SQLAlchemy AppenderQuery object
+ """
+ for column, value in filters.items():
+ # If there are multiple values, use `in_`, otherwise, use `eq`
+ if isinstance(value, (list, tuple)):
+ query = query.filter(column.in_(value))
+ else:
+ query = query.filter(column == value)
+
+ return query
+
+ def _get_query(self,
+ include=None,
+ filters=None,
+ sort=None):
+ """Get an SQL query object based on the params passed
+
+ :param include: An optional list of columns to include in the query
+ :param filters: An optional dictionary where keys are column names to
+ filter by, and values are values applicable for those columns (or lists
+ of such values)
+ :param sort: An optional dictionary where keys are column names to
+ sort by, and values are the order (asc/desc)
+ :return: A sorted and filtered query with only the relevant
+ columns
+ """
+
+ include = include or []
+ filters = filters or dict()
+ sort = sort or OrderedDict()
+
+ joins = self._get_join_models_list(include, filters, sort)
+ include, filters, sort = self._get_columns_from_field_names(
+ include, filters, sort
+ )
+
+ query = self._get_base_query(include, joins)
+ query = self._filter_query(query, filters)
+ query = self._sort_query(query, sort)
+ return query
+
+ def _get_columns_from_field_names(self,
+ include,
+ filters,
+ sort):
+ """Go over the optional parameters (include, filters, sort), and
+ replace column names with actual SQLA column objects
+ """
+ all_includes = [self._get_column(c) for c in include]
+ include = []
+ # Columns that are inferred from properties (Labels) should be included
+ # last for the following joins to work properly
+ for col in all_includes:
+ if isinstance(col, Label):
+ include.append(col)
+ else:
+ include.insert(0, col)
+
+ filters = {self._get_column(c): filters[c] for c in filters}
+ sort = OrderedDict((self._get_column(c), sort[c]) for c in sort)
+
+ return include, filters, sort
+
+ def _get_join_models_list(self, include, filters, sort):
+ """Return a list of models on which the query should be joined, as
+ inferred from the include, filter and sort column names
+ """
+ if not self.model_cls.is_resource:
+ return []
+
+ all_column_names = include + filters.keys() + sort.keys()
+ join_columns = {column_name for column_name in all_column_names
+ if self._is_join_column(column_name)}
+
+ # If the only columns included are the columns on which we would
+ # normally join, there isn't actually a need to join, as the FROM
+ # clause in the query will be generated from the relevant models anyway
+ if include == list(join_columns):
+ return []
+
+ # Initializing a set, because the same model can appear in several
+ # join lists
+ join_models = set()
+ for column_name in join_columns:
+ join_models.update(
+ self.model_cls.join_properties[column_name]['models']
+ )
+ # Sort the models by their correct join order
+ join_models = sorted(join_models,
+ key=lambda model: model.join_order, reverse=True)
+
+ return join_models
+
+ def _is_join_column(self, column_name):
+ """Return False if the column name corresponds to a regular SQLA
+ column that `model_class` has.
+ Return True if the column that should be used is a join column (see
+ SQLModelBase for an explanation)
+ """
+ return self.model_cls.is_resource and \
+ column_name in self.model_cls.join_properties
+
+ def _get_column(self, column_name):
+ """Return the column on which an action (filtering, sorting, etc.)
+ would need to be performed. Can be either an attribute of the class,
+ or needs to be inferred from the class' `join_properties` property
+ """
+ if self._is_join_column(column_name):
+ return self.model_cls.join_properties[column_name]['column']
+ else:
+ return getattr(self.model_cls, column_name)
+
+ # TODO is this really needed in aria?
+ @staticmethod
+ def _paginate(query, pagination):
+ """Paginate the query by size and offset
+
+ :param query: Current SQLAlchemy query object
+ :param pagination: An optional dict with size and offset keys
+ :return: A tuple with four elements:
+ - results: `size` items starting from `offset`
+ - the total count of items
+ - `size` [default: 0]
+ - `offset` [default: 0]
+ """
+ if pagination:
+ size = pagination.get('size', 0)
+ offset = pagination.get('offset', 0)
+ total = query.order_by(None).count() # Fastest way to count
+ results = query.limit(size).offset(offset).all()
+ return results, total, size, offset
+ else:
+ results = query.all()
+ return results, len(results), 0, 0
+
+ @staticmethod
+ def _load_properties(instance):
+ """A helper method used to overcome a problem where the properties
+ that rely on joins aren't being loaded automatically
+ """
+ if instance.is_resource:
+ for prop in instance.join_properties:
+ getattr(instance, prop)
+
+
+class ListResult(object):
+ """
+ a ListResult contains results about the requested items.
+ """
+ def __init__(self, items, metadata):
+ self.items = items
+ self.metadata = metadata
+
+ def __len__(self):
+ return len(self.items)
+
+ def __iter__(self):
+ return iter(self.items)
+
+ def __getitem__(self, item):
+ return self.items[item]