First commit of Tooz

For now the project is composed of a simple API and
use ZooKeeper as the first backend.

Created files:
    - tooz/api.py: the python public API and the abstract class
to implement for backends.

    - tooz/drivers/zookeeper.py: the ZooKeeper backend using the
Kazoo client.

    - tooz/exceptions.py: additional exception will be defined here.

    - tooz/models.py: read only classes, for now the Member class.

    - tooz/tests/test_api.py: Tooz will provide a unique unit-tests suite
which will be run against all backends (thanks to testscenarios).

Change-Id: I4e4cefb52cf6c39a3f6ba35ab1d4ef34a77b5811
This commit is contained in:
Yassine Lamgarchal 2013-12-06 13:17:29 +01:00
parent 9f065c444a
commit db1708709f
12 changed files with 643 additions and 0 deletions

21
.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
*.pyc
*.dat
TAGS
*.egg-info
build
.coverage
.tox
cover
.testrepository
subunit.log
AUTHORS
ChangeLog
*.deb
dist
*.egg
tooz/versioninfo
doc/source/api/tooz.*.rst
doc/source/api/tests.*.rst
doc/source/api/autoindex.rst
doc/source/sourcecode
*.mo

176
LICENSE Normal file
View File

@ -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.

6
README.rst Normal file
View File

@ -0,0 +1,6 @@
tooz
====
The Tooz project aims to centralize 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.

23
setup.cfg Normal file
View File

@ -0,0 +1,23 @@
[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
Topic :: System :: Distributed Computing
[files]
packages =
tooz
[entry_points]
tooz.backends =
zookeeper = tooz.drivers.zookeeper:ZooKeeperDriver

24
setup.py Normal file
View File

@ -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)

0
tooz/__init__.py Normal file
View File

163
tooz/api.py Normal file
View File

@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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):
"""Start the service engine.
If needed, the establishment of a connection to the servers
is initiated.
"""
pass
@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.
"""
pass
@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
"""
pass
@abc.abstractmethod
def get_all_groups_ids(self):
"""Return the list composed by all created groups ids."""
pass
@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
"""
pass
@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
"""
pass
@abc.abstractmethod
def get_members(self):
"""Return the list of all members of the specified group."""
pass
@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
"""
pass
@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
"""
pass
class Coordinator(CoordinationDriver):
#TODO(yassine)
#Replace kwargs by something more simple.
def __init__(self, backend, member_id, kwargs):
"""Initialize and load the backend.
:param backend: the current tooz provided backends are 'zookeeper'
:param member_id: the id of the member
:param kwargs: additional backend specific options
"""
mgr = driver.DriverManager(namespace=TOOZ_BACKENDS_NAMESPACE,
name=backend,
invoke_on_load=True,
invoke_args=(member_id,),
invoke_kwds=kwargs)
self._driver = mgr.driver
def start(self):
self._driver.start()
def stop(self):
self._driver.stop()
def create_group(self, group_id):
self._driver.create_group(group_id)
def get_all_groups_ids(self):
return self._driver.get_all_groups_ids()
def join_group(self, group_id, capabilities=""):
self._driver.join_group(group_id, capabilities)
def leave_group(self, group_id):
self._driver.leave_group(group_id)
def get_members(self, group_id):
return self._driver.get_members(group_id)
#TODO(yassine)
#set default value of member_id to the current member
def get_member_capabilities(self, group_id, member_id):
return self._driver.get_member_capabilities(group_id, member_id)
def update_capabilities(self, group_id, capabilities):
self._driver.update_capabilities(group_id, capabilities)
class InvalidGroup(Exception):
pass
class GroupAlreadyExist(Exception):
pass

0
tooz/drivers/__init__.py Normal file
View File

86
tooz/drivers/zookeeper.py Normal file
View File

@ -0,0 +1,86 @@
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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.protocol import paths
from tooz import api
from tooz import models
_TOOZ_NAMESPACE = "tooz"
class ZooKeeperDriver(api.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"] and 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):
self._coord.start()
self._coord.ensure_path("/%s" % _TOOZ_NAMESPACE)
def stop(self):
self._coord.stop()
def create_group(self, group_id):
try:
self._coord.create("/%s/%s" % (_TOOZ_NAMESPACE, group_id))
except exceptions.NodeExistsError:
raise api.GroupAlreadyExist("group_id=%s" % group_id)
def join_group(self, group_id, capabilities=""):
self._coord.create(self._path_member(group_id, self._member_id),
value=capabilities, ephemeral=True)
def leave_group(self, group_id):
self._coord.delete(self._path_member(group_id, self._member_id))
def get_members(self, group_id):
members = []
member_ids = self._coord.get_children("/%s/%s" % (_TOOZ_NAMESPACE,
group_id))
for member_id in member_ids:
capabilities = self._coord.get(self._path_member(group_id,
member_id))
members.append(models.Member(group_id, member_id, capabilities[0]))
return members
def get_member(self, group_id, member_id):
capabilities = self._coord.get(self._path_member(group_id, member_id))
return models.Member(group_id, member_id, capabilities)
def update_capabilities(self, group_id, capabilities):
self._coord.set(self._path_member(group_id, self._member_id),
capabilities)
def get_member_capabilities(self, group_id, member_id):
return self._coord.get(self._path_member(group_id, member_id))[0]
def get_all_groups_ids(self):
return self._coord.get_children("/%s" % _TOOZ_NAMESPACE)
def _path_member(self, group_id, member_id):
return paths.join("/", _TOOZ_NAMESPACE, group_id, member_id)

32
tooz/models.py Normal file
View File

@ -0,0 +1,32 @@
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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

0
tooz/tests/__init__.py Normal file
View File

112
tooz/tests/test_api.py Normal file
View File

@ -0,0 +1,112 @@
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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
import uuid
import tooz.api
zookeeper_tests = ('zookeeper_tests', {'backend': 'zookeeper',
'kwargs': {'hosts': '127.0.0.1:2181'}})
class TestAPI(testscenarios.TestWithScenarios):
scenarios = [zookeeper_tests]
def setUp(self):
self.group_id = self._get_random_uuid()
self.member_id = self._get_random_uuid()
self._coord = tooz.api.Coordinator(self.backend, self.member_id,
self.kwargs)
self._coord.start()
def tearDown(self):
self._coord.stop()
def test_create_group(self):
self._coord.create_group(self.group_id)
all_group_ids = self._coord.get_all_groups_ids()
self.assertIn(self.group_id, all_group_ids)
def test_get_all_groups_ids(self):
groups_ids = [self._get_random_uuid() for _ in xrange(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.assertIn(group_id, 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.assertIn(self.member_id, 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.assertIn(self.member_id, 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.assertNotIn(self.member_id, new_member_list)
def test_get_members(self):
group_id_test2 = self._get_random_uuid()
member_id_test2 = self._get_random_uuid()
client2 = tooz.api.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.assertIn(self.member_id, members_ids)
self.assertIn(member_id_test2, members_ids)
def test_get_member_capabilities(self):
self._coord.create_group(self.group_id)
self._coord.join_group(self.group_id, "test_capabilities")
capa = self._coord.get_member_capabilities(self.group_id,
self.member_id)
self.assertEqual(capa, "test_capabilities")
def test_update_capabilities(self):
self._coord.create_group(self.group_id)
self._coord.join_group(self.group_id, "test_capabilities1")
capa = self._coord.get_member_capabilities(self.group_id,
self.member_id)
self.assertEqual(capa, "test_capabilities1")
self._coord.update_capabilities(self.group_id,
"test_capabilities2")
capa2 = self._coord.get_member_capabilities(self.group_id,
self.member_id)
self.assertEqual(capa2, "test_capabilities2")
def _get_random_uuid(self):
return str(uuid.uuid4())