From d1e094f61c8a5079759f6eb8960b234700112d6b Mon Sep 17 00:00:00 2001 From: Yassine Lamgarchal Date: Fri, 6 Dec 2013 13:17:29 +0100 Subject: [PATCH] First commit of Tooz For now Tooz is composed of a simple API and use ZooKeeper as the first backend. The current API provide the group membership protocol like 'servicegroup' in Nova, we enriched it by adding the notion of capabilities. The API is currently synchronous, we plan to design an asynchronous one. The notification mechanism is not yet available. Please read the associated blueprint for more details: https://wiki.openstack.org/wiki/Oslo/blueprints/service-sync All new backends must implement api.CoordinationDriver and validate the unit tests. Tooz will provide a unique unit-tests suite which will be run against all backends. Change-Id: I4e4cefb52cf6c39a3f6ba35ab1d4ef34a77b5811 --- .gitignore | 5 + .testr.conf | 4 + LICENSE | 176 ++++++++++++++++++++++++++++++++ README.rst | 6 ++ requirements.txt | 4 + run_tests.sh | 52 ++++++++++ setup.cfg | 27 +++++ setup.py | 24 +++++ test-requirements.txt | 9 ++ tooz/__init__.py | 0 tooz/coordination.py | 164 +++++++++++++++++++++++++++++ tooz/drivers/__init__.py | 0 tooz/drivers/zookeeper.py | 168 ++++++++++++++++++++++++++++++ tooz/models.py | 30 ++++++ tooz/tests/__init__.py | 0 tooz/tests/test_coordination.py | 118 +++++++++++++++++++++ tox.ini | 31 ++++++ 17 files changed, 818 insertions(+) create mode 100644 .gitignore create mode 100644 .testr.conf create mode 100644 LICENSE create mode 100644 README.rst create mode 100644 requirements.txt create mode 100755 run_tests.sh create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 test-requirements.txt create mode 100644 tooz/__init__.py create mode 100644 tooz/coordination.py create mode 100644 tooz/drivers/__init__.py create mode 100644 tooz/drivers/zookeeper.py create mode 100644 tooz/models.py create mode 100644 tooz/tests/__init__.py create mode 100644 tooz/tests/test_coordination.py create mode 100644 tox.ini diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..2f496394 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.pyc +*.egg-info +build +.egg +.tox diff --git a/.testr.conf b/.testr.conf new file mode 100644 index 00000000..63781d3d --- /dev/null +++ b/.testr.conf @@ -0,0 +1,4 @@ +[DEFAULT] +test_command=${PYTHON:-python} -m subunit.run discover tooz $LISTOPT $IDOPTION +test_id_option=--load-list $IDFILE +test_list_option=--list diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..68c771a0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + diff --git a/README.rst b/README.rst new file mode 100644 index 00000000..b9df70ba --- /dev/null +++ b/README.rst @@ -0,0 +1,6 @@ +tooz +==== + +The Tooz project aims at centralizing the most common distributed primitives +like group membership protocol, lock service and leader election by providing +a coordination API helping developers to build distributed applications. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..e766e7a8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +pbr>=0.5.23 +stevedore>=0.13 +six>=1.4.1 +kazoo==1.3.1 diff --git a/run_tests.sh b/run_tests.sh new file mode 100755 index 00000000..6d541d4e --- /dev/null +++ b/run_tests.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -e + +ZOO_CONF=/etc/zookeeper +ZOO_DIR=/usr/share/zookeeper +ZOO_BIN=$ZOO_DIR/bin +ZOO_TMP_DIR=$(mktemp -d /tmp/ZOO-TMP-XXXXX) + +mkdir $ZOO_TMP_DIR/bin + +function clean_exit(){ + local error_code="$?" + if [ -d $ZOO_CONF ]; then + stop_zookeeper_server + fi + rm -rf ${ZOO_TMP_DIR} + return $error_code + +} + + +function start_zookeeper_server(){ + #Copy zookeeper scripts in temporary directory + cp $ZOO_BIN/* $ZOO_TMP_DIR/bin + + #Copy zookeeper conf and set dataDir variable to the zookeeper temporary + #directory + cp $ZOO_CONF/conf/zoo.cfg $ZOO_TMP_DIR + sed -i -r "s@(dataDir *= *).*@\1$ZOO_TMP_DIR@" $ZOO_TMP_DIR/zoo.cfg + + #Replace some variables by the zookeeper temporary directory + sed -i -r "s@(ZOOCFGDIR *= *).*@\1$ZOO_TMP_DIR@" $ZOO_TMP_DIR/bin/zkEnv.sh + + mkdir $ZOO_TMP_DIR/log + sed -i -r "s@(ZOO_LOG_DIR *= *).*@\1$ZOO_TMP_DIR/log@" $ZOO_TMP_DIR/bin/zkEnv.sh + + $ZOO_TMP_DIR/bin/zkServer.sh start +} + + +function stop_zookeeper_server(){ + + $ZOO_TMP_DIR/bin/zkServer.sh stop +} + +trap "clean_exit" EXIT + +if [ -d $ZOO_CONF ]; then + start_zookeeper_server +fi + +python setup.py testr --slowest diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 00000000..dc6d6757 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,27 @@ +[metadata] +name = tooz +author = Tooz developers +author-email = tooz-dev@lists.launchpad.net +summary = Coordination library for distributed systems. +description-file = README.rst +license = Apache-2 +classifier = + Environment :: OpenStack + Intended Audience :: Developers + Intended Audience :: Information Technology + License :: OSI Approved :: Apache Software License + Operating System :: POSIX :: Linux + Programming Language :: Python + Programming Language :: Python :: 2 + Programming Language :: Python :: 2.6 + Programming Language :: Python :: 2.7 + Programming Language :: Python :: 3.3 + Topic :: System :: Distributed Computing + +[files] +packages = + tooz + +[entry_points] +tooz.backends = + zookeeper = tooz.drivers.zookeeper:ZooKeeperDriver diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..304401d2 --- /dev/null +++ b/setup.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. +# +# Licensed 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. + +# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT + +import setuptools + + +setuptools.setup( + setup_requires=['pbr'], + pbr=True) diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 00000000..bc4159fd --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,9 @@ +pep8>=1.4.5 +pyflakes>=0.7.2,<0.7.4 +flake8>=2.1.0 +hacking>=0.8.0,<0.9 +discover +python-subunit +testrepository>=0.0.17 +testtools>=0.9.32 +testscenarios>=0.4 diff --git a/tooz/__init__.py b/tooz/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tooz/coordination.py b/tooz/coordination.py new file mode 100644 index 00000000..1a5bd8f5 --- /dev/null +++ b/tooz/coordination.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 eNovance Inc. All Rights Reserved. +# +# Licensed 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 abc +import six + +from stevedore import driver + +TOOZ_BACKENDS_NAMESPACE = "tooz.backends" + + +@six.add_metaclass(abc.ABCMeta) +class CoordinationDriver(object): + + @abc.abstractmethod + def start(self, timeout): + """Start the service engine. + + If needed, the establishment of a connection to the servers + is initiated. + + :param timeout: Time in seconds to wait for connection to succeed. + :type timeout: int + """ + + @abc.abstractmethod + def stop(self): + """Stop the service engine. + + If needed, the connection to servers is closed and the client will + disappear from all joined groups. + """ + + @abc.abstractmethod + def create_group(self, group_id): + """Request the creation of a group. + + :param group_id: the id of the group to create + :type group_id: str + """ + + @abc.abstractmethod + def get_all_groups_ids(self): + """Return the list composed by all created groups ids. + + :returns: list of all created group ids + :rtype: list + """ + + @abc.abstractmethod + def join_group(self, group_id, capabilities): + """Join a group and establish group membership. + + :param group_id: the id of the group to join + :type group_id: str + :param capabilities: the capabilities of the joined member + :type capabilities: str + """ + + @abc.abstractmethod + def leave_group(self, group_id): + """Leave a group. + + :param group_id: the id of the group to leave + :type group_id: str + """ + + @abc.abstractmethod + def get_members(self): + """Return the list of all members of the specified group. + + :returns: list of all created group ids + :rtype: list + """ + + @abc.abstractmethod + def get_member_capabilities(self, group_id, member_id): + """Return the capabilities of a member. + + :param group_id: the id of the group of the member + :type group_id: str + :param member_id: the id of the member + :type member_id: str + :returns: capabilities of a member + :rtype: str + """ + + @abc.abstractmethod + def update_capabilities(self, group_id, capabilities): + """Update capabilities of the caller in the specified group. + + :param group_id: the id of the group of the current member + :type group_id: str + :param capabilities: the capabilities of the updated member + :type capabilities: str + """ + + + #TODO(yassine) + #Replace kwargs by something more simple. +def get_coordinator(backend, member_id, **kwargs): + """Initialize and load the backend. + + :param backend: the current tooz provided backends are 'zookeeper' + :type backend: str + :param member_id: the id of the member + :type member_id: str + :param kwargs: additional backend specific options + :type kwargs: dict + """ + return driver.DriverManager(namespace=TOOZ_BACKENDS_NAMESPACE, + name=backend, + invoke_on_load=True, + invoke_args=(member_id,), + invoke_kwds=kwargs).driver + + +class ToozError(Exception): + """Exception raised when an internal error occurs, for instance in + case of server internal error. + """ + + +class ToozConnectionError(ToozError): + """Exception raised when the client cannot manage to connect to the + server. + """ + + +class GroupNotCreated(ToozError): + """Exception raised when the caller request a group which does + not exist. + """ + + +class GroupAlreadyExist(ToozError): + """Exception raised when the caller try to create a group which already + exist. + """ + + +class MemberAlreadyExist(ToozError): + """Exception raised when the caller try to join a group but a member + with the same identifier belongs to that group. + """ + + +class MemberNotJoined(ToozError): + """Exception raised when the caller try to access a member which does not + belongs to the specified group. + """ diff --git a/tooz/drivers/__init__.py b/tooz/drivers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tooz/drivers/zookeeper.py b/tooz/drivers/zookeeper.py new file mode 100644 index 00000000..f5023645 --- /dev/null +++ b/tooz/drivers/zookeeper.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 eNovance Inc. All Rights Reserved. +# +# Licensed 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 kazoo import client +from kazoo import exceptions +from kazoo.handlers import threading +from kazoo.protocol import paths + +from tooz import coordination +from tooz import models + +_TOOZ_NAMESPACE = "tooz" + + +class ZooKeeperDriver(coordination.CoordinationDriver): + + def __init__(self, member_id, **kwargs): + """:param kwargs: it must contains the key "hosts" associated + to the list of zookeeper servers in the form "ip:port2, ip2:port2". + """ + if not all((kwargs["hosts"], member_id)): + raise KeyError("hosts=%r, member_id=%r" % (kwargs["hosts"], + member_id)) + self._member_id = member_id + self._coord = client.KazooClient(hosts=kwargs["hosts"]) + super(ZooKeeperDriver, self).__init__() + + def start(self, timeout=10): + try: + self._coord.start(timeout=timeout) + except threading.TimeoutError as e: + raise coordination.ToozConnectionError("operation error: %s" % (e)) + + try: + self._coord.ensure_path(paths.join("/", _TOOZ_NAMESPACE)) + except exceptions.KazooException as e: + raise coordination.ToozError("operation error: %s" % (e)) + + def stop(self): + self._coord.stop() + + def create_group(self, group_id): + try: + group_path = "/%s/%s" % (_TOOZ_NAMESPACE, group_id) + self._wrap_kazoo_call(self._coord.create, group_path) + except exceptions.NodeExistsError: + raise coordination.GroupAlreadyExist("group_id=%s" % group_id) + except exceptions.NoNodeError: + raise coordination.ToozError("tooz namespace has not been created") + + def join_group(self, group_id, capabilities=b""): + try: + member_path = self._path_member(group_id, self._member_id) + self._wrap_kazoo_call(self._coord.create, + member_path, + value=capabilities, + ephemeral=True) + except exceptions.NodeExistsError: + raise coordination.MemberAlreadyExist(str(self._member_id)) + except exceptions.NoNodeError: + raise coordination.GroupNotCreated("group '%s' has not been " + "created" % _TOOZ_NAMESPACE) + + def leave_group(self, group_id): + try: + member_path = self._path_member(group_id, self._member_id) + self._wrap_kazoo_call(self._coord.delete, member_path) + except exceptions.NoNodeError: + raise coordination.MemberNotJoined("member '%s' has not joined " + "the group '%s' or the group " + "has not been created" % + (self._member_id, group_id)) + except exceptions.ZookeeperError as e: + raise coordination.ToozError(str(e)) + + def get_members(self, group_id): + member_ids = [] + try: + group_path = paths.join("/", _TOOZ_NAMESPACE, group_id) + member_ids = self._wrap_kazoo_call(self._coord.get_children, + group_path) + except exceptions.NoNodeError: + raise coordination.GroupNotCreated("group '%s' does not exist" % + group_id) + + members = [] + capabilities = "" + for member_id in member_ids: + try: + member_path = self._path_member(group_id, member_id) + capabilities = self._wrap_kazoo_call(self._coord.get, + member_path) + except exceptions.NoNodeError: + #If the current node does not exist then it means that it + #leaved the group just after the get_children() call above. + pass + members.append(models.Member(group_id, member_id, capabilities[0])) + return members + + def get_member(self, group_id, member_id): + capabilities = "" + try: + member_path = self._path_member(group_id, member_id) + capabilities = self._wrap_kazoo_call(self._coord.get, + member_path)[0] + except exceptions.NoNodeError: + raise coordination.MemberNotJoined("member '%s' has not joined " + "the group '%s' or the group " + "has not been created" % + (member_id, group_id)) + return models.Member(group_id, member_id, capabilities) + + def update_capabilities(self, group_id, capabilities): + try: + member_path = self._path_member(group_id, self._member_id) + self._wrap_kazoo_call(self._coord.set, member_path, capabilities) + except exceptions.NoNodeError: + raise coordination.MemberNotJoined("member '%s' has not joined " + "the group '%s' or the group " + "has not been created" % + (self._member_id, group_id)) + + def get_member_capabilities(self, group_id, member_id): + capabilities = "" + try: + member_path = self._path_member(group_id, member_id) + capabilities = self._wrap_kazoo_call(self._coord.get, + member_path)[0] + except exceptions.NoNodeError: + raise coordination.MemberNotJoined("member '%s' has not joined " + "the group '%s' or the group " + "has not been created" % + (self._member_id, group_id)) + return capabilities + + def get_all_groups_ids(self): + group_ids = [] + try: + group_ids = self._wrap_kazoo_call(self._coord.get_children, + paths.join("/", _TOOZ_NAMESPACE)) + except exceptions.NoNodeError: + raise coordination.ToozError("tooz namespace has " + "not been created") + return group_ids + + @staticmethod + def _path_member(group_id, member_id): + return paths.join("/", _TOOZ_NAMESPACE, group_id, member_id) + + def _wrap_kazoo_call(self, func, *args, **kwargs): + """Call and catch ZooKeeperError.""" + try: + return func(*args, **kwargs) + except exceptions.ZookeeperError as e: + raise coordination.ToozError(str(e)) diff --git a/tooz/models.py b/tooz/models.py new file mode 100644 index 00000000..1f424587 --- /dev/null +++ b/tooz/models.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 eNovance Inc. All Rights Reserved. +# +# Licensed 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. + + +class Member(object): + """The member of a group. + + A member is composed of a member identifier, a group identifier and + capabilities. The capabilities correspond to a bytes string defined by + the user of the API, for instance it could be resulting from JSON + serialization, Google Protocol Buffers, MsgPack and so on. + """ + + def __init__(self, group_id, member_id, capabilities): + self.group_id = group_id + self.member_id = member_id + self.capabilities = capabilities diff --git a/tooz/tests/__init__.py b/tooz/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tooz/tests/test_coordination.py b/tooz/tests/test_coordination.py new file mode 100644 index 00000000..affdbfbb --- /dev/null +++ b/tooz/tests/test_coordination.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2013 eNovance Inc. All Rights Reserved. +# +# Licensed 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 testscenarios +from testtools import testcase +import uuid + +import tooz.coordination + +zookeeper_tests = ('zookeeper_tests', {'backend': 'zookeeper', + 'kwargs': {'hosts': '127.0.0.1:2181'}}) + + +class TestAPI(testscenarios.TestWithScenarios, testcase.TestCase): + + scenarios = [zookeeper_tests] + + def setUp(self): + super(TestAPI, self).setUp() + self.group_id = self._get_random_uuid() + self.member_id = self._get_random_uuid() + self._coord = tooz.coordination.get_coordinator(self.backend, + self.member_id, + **self.kwargs) + try: + self._coord.start(timeout=5) + except tooz.coordination.ToozConnectionError as e: + raise testcase.TestSkipped(str(e)) + + def tearDown(self): + self._coord.stop() + super(TestAPI, self).tearDown() + + def test_create_group(self): + self._coord.create_group(self.group_id) + all_group_ids = self._coord.get_all_groups_ids() + self.assertTrue(self.group_id in all_group_ids) + + def test_get_all_groups_ids(self): + groups_ids = [self._get_random_uuid() for _ in range(0, 5)] + for group_id in groups_ids: + self._coord.create_group(group_id) + created_groups = self._coord.get_all_groups_ids() + for group_id in groups_ids: + self.assertTrue(group_id in created_groups) + + def test_join_group(self): + self._coord.create_group(self.group_id) + self._coord.join_group(self.group_id) + member_objects = self._coord.get_members(self.group_id) + member_list = [member.member_id for member in member_objects] + self.assertTrue(self.member_id in member_list) + + def test_leave_group(self): + self._coord.create_group(self.group_id) + self._coord.join_group(self.group_id) + member_objects = self._coord.get_members(self.group_id) + member_ids = [member.member_id for member in member_objects] + self.assertTrue(self.member_id in member_ids) + self._coord.leave_group(self.group_id) + new_member_objects = self._coord.get_members(self.group_id) + new_member_list = [member.member_id for member in new_member_objects] + self.assertTrue(self.member_id not in new_member_list) + + def test_get_members(self): + group_id_test2 = self._get_random_uuid() + member_id_test2 = self._get_random_uuid() + client2 = tooz.coordination.get_coordinator(self.backend, + member_id_test2, + **self.kwargs) + client2.start() + + self._coord.create_group(group_id_test2) + self._coord.join_group(group_id_test2) + client2.join_group(group_id_test2) + members_objects = self._coord.get_members(group_id_test2) + members_ids = [member.member_id for member in members_objects] + self.assertTrue(self.member_id in members_ids) + self.assertTrue(member_id_test2 in members_ids) + + def test_get_member_capabilities(self): + self._coord.create_group(self.group_id) + self._coord.join_group(self.group_id, b"test_capabilities") + + capa = self._coord.get_member_capabilities(self.group_id, + self.member_id) + self.assertEqual(capa, b"test_capabilities") + + def test_update_capabilities(self): + self._coord.create_group(self.group_id) + self._coord.join_group(self.group_id, b"test_capabilities1") + + capa = self._coord.get_member_capabilities(self.group_id, + self.member_id) + self.assertEqual(capa, b"test_capabilities1") + self._coord.update_capabilities(self.group_id, + b"test_capabilities2") + + capa2 = self._coord.get_member_capabilities(self.group_id, + self.member_id) + self.assertEqual(capa2, b"test_capabilities2") + + def _get_random_uuid(self): + return str(uuid.uuid4()) diff --git a/tox.ini b/tox.ini new file mode 100644 index 00000000..a266d382 --- /dev/null +++ b/tox.ini @@ -0,0 +1,31 @@ +[tox] +minversion = 1.6 +skipsdist = True +envlist = py26,py27,py33,pep8 + +[testenv] +deps = -r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt +install_command = pip install -U {opts} {packages} +usedevelop = True +commands = + bash -x {toxinidir}/run_tests.sh {posargs} + + +[testenv:venv] +deps = -r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt +commands = {posargs} + +[testenv:pep8] +# Install bounded pep8/pyflakes first, then let flake8 install +deps = pep8==1.4.5 + pyflakes==0.7.2 + flake8==2.0 + hacking>=0.8.0,<0.9 +commands = + flake8 + +[flake8] +exclude=.venv,.git,.tox,dist,*egg,*.egg-info,build +show-source = True