Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / lib / pool / __init__.py @ e66c7993

History | View | Annotate | Download (4.7 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34

    
35
"""Classes to support pools of arbitrary objects.
36

37
The :class:`ObjectPool` class in this module abstracts a pool
38
of arbitrary objects. Subclasses need to define the details regarding
39
creation, destruction, allocation and release of their specific objects.
40

41
"""
42

    
43
# This should work under gevent, because gevent monkey patches 'threading'
44
# if not, we can detect if running under gevent, e.g. using
45
# if 'gevent' in sys.modules:
46
#     from gevent.coros import Semaphore
47
# else:
48
#     from threading import Semaphore
49
from threading import Semaphore, Lock
50

    
51

    
52
__all__ = ['ObjectPool', 'ObjectPoolError', 'PoolEmptyError']
53

    
54

    
55
class ObjectPoolError(Exception):
56
    pass
57

    
58

    
59
class PoolEmptyError(ObjectPoolError):
60
    pass
61

    
62

    
63
class ObjectPool(object):
64
    def __init__(self, size=None):
65
        try:
66
            self.size = int(size)
67
            assert size >= 1
68
        except:
69
            raise ValueError("Invalid size for pool (positive integer "
70
                             "required): %r" % (size,))
71

    
72
        self._semaphore = Semaphore(size)  # Pool grows up to size
73
        self._mutex = Lock()  # Protect shared _set oject
74
        self._set = set()
75

    
76
    def pool_get(self, blocking=True, timeout=None, create=True):
77
        """Get an object from the pool.
78

79
        Get an object from the pool. By default (create=True), create a new
80
        object if the pool has not reached its maximum size yet. If
81
        create == False, the caller is responsible for creating the object and
82
        put()ting it back into the pool when done.
83

84
        """
85
        # timeout argument only supported by gevent and py3k variants
86
        # of Semaphore. acquire() will raise TypeError if timeout
87
        # is specified but not supported by the underlying implementation.
88
        kw = {"blocking": blocking}
89
        if timeout is not None:
90
            kw["timeout"] = timeout
91
        r = self._semaphore.acquire(**kw)
92
        if not r:
93
            raise PoolEmptyError()
94
        with self._mutex:
95
            try:
96
                try:
97
                    obj = self._set.pop()
98
                except KeyError:
99
                    obj = self._pool_create() if create else None
100
            except:
101
                self._semaphore.release()
102
                raise
103
        # We keep _semaphore locked, put() will release it
104
        return obj
105

    
106
    def pool_put(self, obj):
107
        """Put an object back into the pool.
108

109
        Return an object to the pool, for subsequent retrieval
110
        by pool_get() calls. If _pool_cleanup() returns True,
111
        the object has died and is not put back into self._set.
112

113
        """
114
        if not self._pool_cleanup(obj):
115
            with self._mutex:
116
                self._set.add(obj)
117
        self._semaphore.release()
118

    
119
    def _pool_create(self):
120
        """Create a new object to be used with this pool.
121

122
        Create a new object to be used with this pool,
123
        should be overriden in subclasses.
124

125
        """
126
        raise NotImplementedError
127

    
128
    def _pool_cleanup(self, obj):
129
        """Cleanup an object before being put back into the pool.
130

131
        Cleanup an object before it can be put back into the pull,
132
        ensure it is in a stable, reusable state.
133

134
        """
135
        raise NotImplementedError