Debian Codegraph @

src/bonsai/pool.py

raw symbols SCIP
1 import logging
2 import threading
3 from contextlib import contextmanager
4 from typing import Optional, Any, Set, Generic, TypeVar, Generator
5
6 from .ldapconnection import BaseLDAPConnection, LDAPConnection
7
8 MYPY = False
9
10 if MYPY:
11 from .ldapclient import LDAPClient
12
13
14 logger = logging.getLogger("bonsai.pool")
15
16
17 class PoolError(Exception):
18 """Connection pool related errors."""
19
20 pass
21
22
23 class ClosedPool(PoolError):
24 """Raised, when the connection pool is closed."""
25
26 pass
27
28
29 class EmptyPool(PoolError):
30 """Raised, when the connection pool is empty."""
31
32 pass
33
34
35 T = TypeVar("T", bound=BaseLDAPConnection)
36
37
38 class ConnectionPool(Generic[T]):
39 """
40 A connection pool object for managing multiple open connections.
41
42 :param LDAPClient client: the :class:`bonsai.LDAPClient` that's used to create
43 connections.
44 :param int minconn: the minimum number of connections that's created
45 after the pool is opened.
46 :param int maxconn: the maximum number of connections in the pool.
47 :param \\*\\*kwargs: additional keyword arguments that are passed to
48 the :meth:`bonsai.LDAPClient.connect` method.
49 :raises ValueError: when the minconn is negative or the maxconn is less
50 than the minconn.
51 """
52
53 def __init__(
54 self, client: "LDAPClient", minconn: int = 1, maxconn: int = 10, **kwargs: Any
55 ) -> None:
56 """Init method."""
57 if minconn < 0:
58 raise ValueError("The minconn must be positive.")
59 if minconn > maxconn:
60 raise ValueError("The maxconn must be greater than minconn.")
61 self._minconn = minconn
62 self._maxconn = maxconn
63 self._client = client
64 self._kwargs = kwargs
65 self._closed = True
66 self._idles: Set[T] = set()
67 self._used: Set[T] = set()
68
69 def open(self) -> None:
70 """
71 Open the connection pool by initialising the minimal number of
72 connections.
73 """
74 for _ in range(self._minconn - self.idle_connection - self.shared_connection):
75 self._idles.add(self._client.connect(**self._kwargs))
76 self._closed = False
77
78 def get(self) -> T:
79 """
80 Get a connection from the connection pool.
81
82 :raises EmptyPool: when the pool is empty.
83 :raises ClosedPool: when the method is called on a closed pool.
84 :return: an LDAP connection object.
85 """
86 if self._closed:
87 raise ClosedPool("The pool is closed.")
88 try:
89 conn = self._idles.pop()
90 except KeyError:
91 if len(self._used) < self._maxconn:
92 conn = self._client.connect(**self._kwargs)
93 else:
94 raise EmptyPool("Pool is empty.") from None
95 self._used.add(conn)
96 return conn
97
98 def put(self, conn: T) -> None:
99 """
100 Put back a connection to the connection pool. The caller is allowed to
101 close the connection (if, for instance, it is in an error state), in
102 which case it's not returned to the pool and a subsequent get will
103 grow the pool if needed.
104
105 :param LDAPConnection conn: the connection managed by the pool.
106 :raises ClosedPool: when the method is called on a closed pool.
107 :raises PoolError: when tying to put back an object that's not managed
108 by this pool.
109 """
110 if self._closed:
111 raise ClosedPool("The pool is closed.")
112 try:
113 self._used.remove(conn)
114 if not conn.closed:
115 self._idles.add(conn)
116 except KeyError:
117 raise PoolError("The %r is not managed by this pool." % conn) from None
118
119 def close(self) -> None:
120 """Close the pool and all of its managed connections."""
121 for conn in self._idles:
122 try:
123 conn.close()
124 except Exception as exc:
125 logger.warning(
126 f"Exception is raised during closing idle connection: {exc}"
127 )
128 for conn in self._used:
129 try:
130 conn.close()
131 except Exception as exc:
132 logger.warning(
133 f"Exception is raised during closing used connection: {exc}"
134 )
135 self._closed = True
136 self._idles = set()
137 self._used = set()
138
139 @contextmanager
140 def spawn(self, *args: Any, **kwargs: Any) -> Generator[T, None, None]:
141 """
142 Context manager method that acquires a connection from the pool
143 and returns it on exit. It also opens the pool if it hasn't been
144 opened before.
145
146 :params \\*args: the positional arguments passed to
147 :meth:`bonsai.pool.ConnectionPool.get`.
148 :params \\*\\*kwargs: the keyword arguments passed to
149 :meth:`bonsai.pool.ConnectionPool.get`.
150 """
151 conn = None
152 try:
153 if self._closed:
154 self.open()
155 conn = self.get(*args, **kwargs)
156 yield conn
157 finally:
158 if conn:
159 self.put(conn)
160
161 @property
162 def empty(self) -> bool:
163 """
164 Read-only property that will be True when the connection pool has
165 no free connection to use.
166 """
167 return len(self._idles) == 0 and len(self._used) == self._maxconn
168
169 @property
170 def closed(self) -> bool:
171 """
172 Read-only property that will be True when the connection pool has
173 been closed.
174 """
175 return self._closed
176
177 @property
178 def shared_connection(self) -> int:
179 """The number of shared connections."""
180 return len(self._used)
181
182 @property
183 def idle_connection(self) -> int:
184 """the number of idle connection."""
185 return len(self._idles)
186
187 @property
188 def max_connection(self) -> int:
189 """The maximal number of connections that the pool can have."""
190 return self._maxconn
191
192 @max_connection.setter
193 def max_connection(self, val: int) -> None:
194 """The maximal number of connections that the pool can have."""
195 if val < self._minconn:
196 raise ValueError("The maxconn must be greater than minconn.")
197 self._maxconn = val
198
199
200 class ThreadedConnectionPool(ConnectionPool[LDAPConnection]):
201 """
202 A connection pool that can be shared between threads. It's inherited from
203 :class:`bonsai.pool.ConnectionPool`.
204
205 :param LDAPClient client: the :class:`bonsai.LDAPClient` that's used to create
206 connections.
207 :param int minconn: the minimum number of connections that's created
208 after the pool is opened.
209 :param int maxconn: the maximum number of connections in the pool.
210 :param bool block: when it's True, the get method will block when no
211 connection is available in the pool.
212 :param \\*\\*kwargs: additional keyword arguments that are passed to
213 the :meth:`bonsai.LDAPClient.connect` method.
214 :raises ValueError: when the minconn is negative or the maxconn is less
215 than the minconn.
216 """
217
218 def __init__(
219 self,
220 client: "LDAPClient",
221 minconn: int = 1,
222 maxconn: int = 10,
223 block: bool = True,
224 **kwargs: Any,
225 ) -> None:
226 """Init method."""
227 super().__init__(client, minconn, maxconn, **kwargs)
228 self._block = block
229 self._lock = threading.Condition()
230
231 def get(self, timeout: Optional[float] = None) -> LDAPConnection:
232 """
233 Get a connection from the connection pool.
234
235 :param float timeout: a timeout until waiting for free connection.
236 :raises EmptyPool: when the pool is empty.
237 :raises ClosedPool: when the method is called on a closed pool.
238 :return: an LDAP connection object.
239 """
240 with self._lock:
241 if self._block:
242 self._lock.wait_for(lambda: not self.empty or self._closed, timeout)
243 conn = super().get()
244 self._lock.notify()
245 return conn
246
247 def put(self, conn: LDAPConnection) -> None:
248 with self._lock:
249 super().put(conn)
250 self._lock.notify()
251
252 def close(self) -> None:
253 with self._lock:
254 super().close()
255 self._lock.notify_all()
256
257 def open(self) -> None:
258 with self._lock:
259 super().open()