root / snf-common / synnefo / lib / pool / __init__.py @ 5f6ad491
History | View | Annotate | Download (7.9 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', |
53 |
'PoolLimitError', 'PoolVerificationError' ] |
54 |
|
55 |
import logging |
56 |
log = logging.getLogger(__name__) |
57 |
|
58 |
|
59 |
class ObjectPoolError(Exception): |
60 |
pass
|
61 |
|
62 |
class PoolLimitError(ObjectPoolError): |
63 |
pass
|
64 |
|
65 |
class PoolVerificationError(ObjectPoolError): |
66 |
pass
|
67 |
|
68 |
|
69 |
class ObjectPool(object): |
70 |
"""Generic Object Pool.
|
71 |
|
72 |
The pool consists of an object set and an allocation semaphore.
|
73 |
|
74 |
pool_get() gets an allocation from the semaphore
|
75 |
and an object from the pool set.
|
76 |
|
77 |
pool_put() releases an allocation to the semaphore
|
78 |
and puts an object back to the pool set.
|
79 |
|
80 |
Subclasses must implement these thread-safe hooks:
|
81 |
_pool_create()
|
82 |
is used as a subclass hook to auto-create new objects in pool_get().
|
83 |
_pool_verify()
|
84 |
verifies objects before they are returned by pool_get()
|
85 |
_pool_cleanup()
|
86 |
cleans up and verifies objects before their return by pool_put().
|
87 |
|
88 |
While allocations are strictly accounted for and limited by
|
89 |
the semaphore, objects are expendable:
|
90 |
|
91 |
The hook provider and the caller are solely responsible for object handling.
|
92 |
pool_get() may create an object if there is none in the pool set.
|
93 |
pool_get() may return no object, leaving object creation to the caller.
|
94 |
pool_put() may return no object to the pool set.
|
95 |
Objects to pool_put() to the pool need not be those from pool_get().
|
96 |
Objects to pool_get() need not be those from pool_put().
|
97 |
|
98 |
|
99 |
Callers beware:
|
100 |
The pool limit size must be greater than the total working set of objects,
|
101 |
otherwise it will hang. When in doubt, use an impossibly large size limit.
|
102 |
Since the pool grows on demand, this will not waste resources.
|
103 |
However, in that case, the pool must not be used as a flow control device
|
104 |
(i.e. relying on pool_get() blocking to stop threads),
|
105 |
as the impossibly large pool size limit will defer blocking until too late.
|
106 |
|
107 |
"""
|
108 |
def __init__(self, size=None): |
109 |
try:
|
110 |
self.size = int(size) |
111 |
assert size >= 1 |
112 |
except:
|
113 |
raise ValueError("Invalid size for pool (positive integer " |
114 |
"required): %r" % (size,))
|
115 |
|
116 |
self._semaphore = Semaphore(size) # Pool grows up to size limit |
117 |
self._mutex = Lock() # Protect shared _set oject |
118 |
self._set = set() |
119 |
log.debug("Initialized pool %r", self) |
120 |
|
121 |
def __repr__(self): |
122 |
return ("<pool %d: size=%d, len(_set)=%d, semaphore=%d>" % |
123 |
(id(self), self.size, len(self._set), |
124 |
self._semaphore._Semaphore__value))
|
125 |
|
126 |
def pool_get(self, blocking=True, timeout=None, create=True, verify=True): |
127 |
"""Get an object from the pool.
|
128 |
|
129 |
Get a pool allocation and an object from the pool set.
|
130 |
Raise PoolLimitError if the pool allocation limit has been reached.
|
131 |
If the pool set is empty, create a new object (create==True),
|
132 |
or return None (create==False) and let the caller create it.
|
133 |
All objects returned (except None) are verified.
|
134 |
|
135 |
"""
|
136 |
# timeout argument only supported by gevent and py3k variants
|
137 |
# of Semaphore. acquire() will raise TypeError if timeout
|
138 |
# is specified but not supported by the underlying implementation.
|
139 |
log.debug("GET: about to get object from pool %r", self) |
140 |
kw = {"blocking": blocking}
|
141 |
if timeout is not None: |
142 |
kw["timeout"] = timeout
|
143 |
sema = self._semaphore
|
144 |
r = sema.acquire(**kw) |
145 |
if not r: |
146 |
raise PoolLimitError()
|
147 |
|
148 |
try:
|
149 |
created = 0
|
150 |
while 1: |
151 |
with self._mutex: |
152 |
try:
|
153 |
obj = self._set.pop()
|
154 |
except KeyError: |
155 |
obj = None
|
156 |
if obj is None and create: |
157 |
obj = self._pool_create()
|
158 |
created = 1
|
159 |
|
160 |
if not self._pool_verify(obj): |
161 |
if created:
|
162 |
m = "Pool %r cannot verify new object %r" % (self, obj) |
163 |
raise PoolVerificationError(m)
|
164 |
continue
|
165 |
break
|
166 |
except:
|
167 |
sema.release() |
168 |
raise
|
169 |
|
170 |
# We keep _semaphore acquired, put() will release it
|
171 |
log.debug("GOT: object %r from pool %r", obj, self) |
172 |
return obj
|
173 |
|
174 |
def pool_put(self, obj): |
175 |
"""Put an object back into the pool.
|
176 |
|
177 |
Release an allocation and return an object to the pool.
|
178 |
If obj is None, or _pool_cleanup returns True,
|
179 |
then the allocation is released,
|
180 |
but no object returned to the pool set
|
181 |
|
182 |
"""
|
183 |
log.debug("PUT-BEFORE: about to put object %r back to pool %r", obj, self) |
184 |
if obj is not None and not self._pool_cleanup(obj): |
185 |
with self._mutex: |
186 |
self._set.add(obj)
|
187 |
self._semaphore.release()
|
188 |
log.debug("PUT-AFTER: finished putting object %r back to pool %r", obj, self) |
189 |
|
190 |
def _pool_create(self): |
191 |
"""Create a new object to be used with this pool.
|
192 |
|
193 |
Create a new object to be used with this pool,
|
194 |
should be overriden in subclasses.
|
195 |
Must be thread-safe.
|
196 |
"""
|
197 |
raise NotImplementedError |
198 |
|
199 |
def _pool_verify(self, obj): |
200 |
"""Verify an object after getting it from the pool.
|
201 |
|
202 |
If it returns False, the object is discarded
|
203 |
and another one is drawn from the pool.
|
204 |
If the pool is empty, a new object is created.
|
205 |
If the new object fails to verify, pool_get() will fail.
|
206 |
Must be thread-safe.
|
207 |
|
208 |
"""
|
209 |
raise NotImplementedError |
210 |
|
211 |
def _pool_cleanup(self, obj): |
212 |
"""Cleanup an object before being put back into the pool.
|
213 |
|
214 |
Cleanup an object before it can be put back into the pull,
|
215 |
ensure it is in a stable, reusable state.
|
216 |
Must be thread-safe.
|
217 |
|
218 |
"""
|
219 |
raise NotImplementedError |