You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

496 line
25 KiB

  1. """
  2. """
  3. # Created on 2014.03.23
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2020 Giovanni Cannata
  8. #
  9. # This file is part of ldap3.
  10. #
  11. # ldap3 is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # ldap3 is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Lesser General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Lesser General Public License
  22. # along with ldap3 in the COPYING and COPYING.LESSER files.
  23. # If not, see <http://www.gnu.org/licenses/>.
  24. from datetime import datetime
  25. from os import linesep
  26. from threading import Thread, Lock
  27. from time import sleep
  28. from .. import RESTARTABLE, get_config_parameter, AUTO_BIND_DEFAULT, AUTO_BIND_NONE, AUTO_BIND_NO_TLS, AUTO_BIND_TLS_AFTER_BIND, AUTO_BIND_TLS_BEFORE_BIND
  29. from .base import BaseStrategy
  30. from ..core.usage import ConnectionUsage
  31. from ..core.exceptions import LDAPConnectionPoolNameIsMandatoryError, LDAPConnectionPoolNotStartedError, LDAPOperationResult, LDAPExceptionError, LDAPResponseTimeoutError
  32. from ..utils.log import log, log_enabled, ERROR, BASIC
  33. from ..protocol.rfc4511 import LDAP_MAX_INT
  34. TERMINATE_REUSABLE = 'TERMINATE_REUSABLE_CONNECTION'
  35. BOGUS_BIND = -1
  36. BOGUS_UNBIND = -2
  37. BOGUS_EXTENDED = -3
  38. BOGUS_ABANDON = -4
  39. try:
  40. from queue import Queue, Empty
  41. except ImportError: # Python 2
  42. # noinspection PyUnresolvedReferences
  43. from Queue import Queue, Empty
  44. # noinspection PyProtectedMember
  45. class ReusableStrategy(BaseStrategy):
  46. """
  47. A pool of reusable SyncWaitRestartable connections with lazy behaviour and limited lifetime.
  48. The connection using this strategy presents itself as a normal connection, but internally the strategy has a pool of
  49. connections that can be used as needed. Each connection lives in its own thread and has a busy/available status.
  50. The strategy performs the requested operation on the first available connection.
  51. The pool of connections is instantiated at strategy initialization.
  52. Strategy has two customizable properties, the total number of connections in the pool and the lifetime of each connection.
  53. When lifetime is expired the connection is closed and will be open again when needed.
  54. """
  55. pools = dict()
  56. def receiving(self):
  57. raise NotImplementedError
  58. def _start_listen(self):
  59. raise NotImplementedError
  60. def _get_response(self, message_id, timeout):
  61. raise NotImplementedError
  62. def get_stream(self):
  63. raise NotImplementedError
  64. def set_stream(self, value):
  65. raise NotImplementedError
  66. # noinspection PyProtectedMember
  67. class ConnectionPool(object):
  68. """
  69. Container for the Connection Threads
  70. """
  71. def __new__(cls, connection):
  72. if connection.pool_name in ReusableStrategy.pools: # returns existing connection pool
  73. pool = ReusableStrategy.pools[connection.pool_name]
  74. if not pool.started: # if pool is not started remove it from the pools singleton and create a new onw
  75. del ReusableStrategy.pools[connection.pool_name]
  76. return object.__new__(cls)
  77. if connection.pool_keepalive and pool.keepalive != connection.pool_keepalive: # change lifetime
  78. pool.keepalive = connection.pool_keepalive
  79. if connection.pool_lifetime and pool.lifetime != connection.pool_lifetime: # change keepalive
  80. pool.lifetime = connection.pool_lifetime
  81. if connection.pool_size and pool.pool_size != connection.pool_size: # if pool size has changed terminate and recreate the connections
  82. pool.terminate_pool()
  83. pool.pool_size = connection.pool_size
  84. return pool
  85. else:
  86. return object.__new__(cls)
  87. def __init__(self, connection):
  88. if not hasattr(self, 'workers'):
  89. self.name = connection.pool_name
  90. self.master_connection = connection
  91. self.workers = []
  92. self.pool_size = connection.pool_size or get_config_parameter('REUSABLE_THREADED_POOL_SIZE')
  93. self.lifetime = connection.pool_lifetime or get_config_parameter('REUSABLE_THREADED_LIFETIME')
  94. self.keepalive = connection.pool_keepalive
  95. self.request_queue = Queue()
  96. self.open_pool = False
  97. self.bind_pool = False
  98. self.tls_pool = False
  99. self._incoming = dict()
  100. self.counter = 0
  101. self.terminated_usage = ConnectionUsage() if connection._usage else None
  102. self.terminated = False
  103. self.pool_lock = Lock()
  104. ReusableStrategy.pools[self.name] = self
  105. self.started = False
  106. if log_enabled(BASIC):
  107. log(BASIC, 'instantiated ConnectionPool: <%r>', self)
  108. def __str__(self):
  109. s = 'POOL: ' + str(self.name) + ' - status: ' + ('started' if self.started else 'terminated')
  110. s += ' - responses in queue: ' + str(len(self._incoming))
  111. s += ' - pool size: ' + str(self.pool_size)
  112. s += ' - lifetime: ' + str(self.lifetime)
  113. s += ' - keepalive: ' + str(self.keepalive)
  114. s += ' - open: ' + str(self.open_pool)
  115. s += ' - bind: ' + str(self.bind_pool)
  116. s += ' - tls: ' + str(self.tls_pool) + linesep
  117. s += 'MASTER CONN: ' + str(self.master_connection) + linesep
  118. s += 'WORKERS:'
  119. if self.workers:
  120. for i, worker in enumerate(self.workers):
  121. s += linesep + str(i).rjust(5) + ': ' + str(worker)
  122. else:
  123. s += linesep + ' no active workers in pool'
  124. return s
  125. def __repr__(self):
  126. return self.__str__()
  127. def get_info_from_server(self):
  128. for worker in self.workers:
  129. with worker.worker_lock:
  130. if not worker.connection.server.schema or not worker.connection.server.info:
  131. worker.get_info_from_server = True
  132. else:
  133. worker.get_info_from_server = False
  134. def rebind_pool(self):
  135. for worker in self.workers:
  136. with worker.worker_lock:
  137. worker.connection.rebind(self.master_connection.user,
  138. self.master_connection.password,
  139. self.master_connection.authentication,
  140. self.master_connection.sasl_mechanism,
  141. self.master_connection.sasl_credentials)
  142. def start_pool(self):
  143. if not self.started:
  144. self.create_pool()
  145. for worker in self.workers:
  146. with worker.worker_lock:
  147. worker.thread.start()
  148. self.started = True
  149. self.terminated = False
  150. if log_enabled(BASIC):
  151. log(BASIC, 'worker started for pool <%s>', self)
  152. return True
  153. return False
  154. def create_pool(self):
  155. if log_enabled(BASIC):
  156. log(BASIC, 'created pool <%s>', self)
  157. self.workers = [ReusableStrategy.PooledConnectionWorker(self.master_connection, self.request_queue) for _ in range(self.pool_size)]
  158. def terminate_pool(self):
  159. if not self.terminated:
  160. if log_enabled(BASIC):
  161. log(BASIC, 'terminating pool <%s>', self)
  162. self.started = False
  163. self.request_queue.join() # waits for all queue pending operations
  164. for _ in range(len([worker for worker in self.workers if worker.thread.is_alive()])): # put a TERMINATE signal on the queue for each active thread
  165. self.request_queue.put((TERMINATE_REUSABLE, None, None, None))
  166. self.request_queue.join() # waits for all queue terminate operations
  167. self.terminated = True
  168. if log_enabled(BASIC):
  169. log(BASIC, 'pool terminated for <%s>', self)
  170. class PooledConnectionThread(Thread):
  171. """
  172. The thread that holds the Reusable connection and receive operation request via the queue
  173. Result are sent back in the pool._incoming list when ready
  174. """
  175. def __init__(self, worker, master_connection):
  176. Thread.__init__(self)
  177. self.daemon = True
  178. self.worker = worker
  179. self.master_connection = master_connection
  180. if log_enabled(BASIC):
  181. log(BASIC, 'instantiated PooledConnectionThread: <%r>', self)
  182. # noinspection PyProtectedMember
  183. def run(self):
  184. self.worker.running = True
  185. terminate = False
  186. pool = self.master_connection.strategy.pool
  187. while not terminate:
  188. try:
  189. counter, message_type, request, controls = pool.request_queue.get(block=True, timeout=self.master_connection.strategy.pool.keepalive)
  190. except Empty: # issue an Abandon(0) operation to keep the connection live - Abandon(0) is a harmless operation
  191. if not self.worker.connection.closed:
  192. self.worker.connection.abandon(0)
  193. continue
  194. with self.worker.worker_lock:
  195. self.worker.busy = True
  196. if counter == TERMINATE_REUSABLE:
  197. terminate = True
  198. if self.worker.connection.bound:
  199. try:
  200. self.worker.connection.unbind()
  201. if log_enabled(BASIC):
  202. log(BASIC, 'thread terminated')
  203. except LDAPExceptionError:
  204. pass
  205. else:
  206. if (datetime.now() - self.worker.creation_time).seconds >= self.master_connection.strategy.pool.lifetime: # destroy and create a new connection
  207. try:
  208. self.worker.connection.unbind()
  209. except LDAPExceptionError:
  210. pass
  211. self.worker.new_connection()
  212. if log_enabled(BASIC):
  213. log(BASIC, 'thread respawn')
  214. if message_type not in ['bindRequest', 'unbindRequest']:
  215. try:
  216. if pool.open_pool and self.worker.connection.closed:
  217. self.worker.connection.open(read_server_info=False)
  218. if pool.tls_pool and not self.worker.connection.tls_started:
  219. self.worker.connection.start_tls(read_server_info=False)
  220. if pool.bind_pool and not self.worker.connection.bound:
  221. self.worker.connection.bind(read_server_info=False)
  222. elif pool.open_pool and not self.worker.connection.closed: # connection already open, issues a start_tls
  223. if pool.tls_pool and not self.worker.connection.tls_started:
  224. self.worker.connection.start_tls(read_server_info=False)
  225. if self.worker.get_info_from_server and counter:
  226. self.worker.connection.refresh_server_info()
  227. self.worker.get_info_from_server = False
  228. response = None
  229. result = None
  230. if message_type == 'searchRequest':
  231. response = self.worker.connection.post_send_search(self.worker.connection.send(message_type, request, controls))
  232. else:
  233. response = self.worker.connection.post_send_single_response(self.worker.connection.send(message_type, request, controls))
  234. result = self.worker.connection.result
  235. with pool.pool_lock:
  236. pool._incoming[counter] = (response, result, BaseStrategy.decode_request(message_type, request, controls))
  237. except LDAPOperationResult as e: # raise_exceptions has raised an exception. It must be redirected to the original connection thread
  238. with pool.pool_lock:
  239. pool._incoming[counter] = (e, None, None)
  240. # pool._incoming[counter] = (type(e)(str(e)), None, None)
  241. # except LDAPOperationResult as e: # raise_exceptions has raised an exception. It must be redirected to the original connection thread
  242. # exc = e
  243. # with pool.pool_lock:
  244. # if exc:
  245. # pool._incoming[counter] = (exc, None, None)
  246. # else:
  247. # pool._incoming[counter] = (response, result, BaseStrategy.decode_request(message_type, request, controls))
  248. self.worker.busy = False
  249. pool.request_queue.task_done()
  250. self.worker.task_counter += 1
  251. if log_enabled(BASIC):
  252. log(BASIC, 'thread terminated')
  253. if self.master_connection.usage:
  254. pool.terminated_usage += self.worker.connection.usage
  255. self.worker.running = False
  256. class PooledConnectionWorker(object):
  257. """
  258. Container for the restartable connection. it includes a thread and a lock to execute the connection in the pool
  259. """
  260. def __init__(self, connection, request_queue):
  261. self.master_connection = connection
  262. self.request_queue = request_queue
  263. self.running = False
  264. self.busy = False
  265. self.get_info_from_server = False
  266. self.connection = None
  267. self.creation_time = None
  268. self.task_counter = 0
  269. self.new_connection()
  270. self.thread = ReusableStrategy.PooledConnectionThread(self, self.master_connection)
  271. self.worker_lock = Lock()
  272. if log_enabled(BASIC):
  273. log(BASIC, 'instantiated PooledConnectionWorker: <%s>', self)
  274. def __str__(self):
  275. s = 'CONN: ' + str(self.connection) + linesep + ' THREAD: '
  276. s += 'running' if self.running else 'halted'
  277. s += ' - ' + ('busy' if self.busy else 'available')
  278. s += ' - ' + ('created at: ' + self.creation_time.isoformat())
  279. s += ' - time to live: ' + str(self.master_connection.strategy.pool.lifetime - (datetime.now() - self.creation_time).seconds)
  280. s += ' - requests served: ' + str(self.task_counter)
  281. return s
  282. def new_connection(self):
  283. from ..core.connection import Connection
  284. # noinspection PyProtectedMember
  285. self.creation_time = datetime.now()
  286. self.connection = Connection(server=self.master_connection.server_pool if self.master_connection.server_pool else self.master_connection.server,
  287. user=self.master_connection.user,
  288. password=self.master_connection.password,
  289. auto_bind=AUTO_BIND_NONE, # do not perform auto_bind because it reads again the schema
  290. version=self.master_connection.version,
  291. authentication=self.master_connection.authentication,
  292. client_strategy=RESTARTABLE,
  293. auto_referrals=self.master_connection.auto_referrals,
  294. auto_range=self.master_connection.auto_range,
  295. sasl_mechanism=self.master_connection.sasl_mechanism,
  296. sasl_credentials=self.master_connection.sasl_credentials,
  297. check_names=self.master_connection.check_names,
  298. collect_usage=self.master_connection._usage,
  299. read_only=self.master_connection.read_only,
  300. raise_exceptions=self.master_connection.raise_exceptions,
  301. lazy=False,
  302. fast_decoder=self.master_connection.fast_decoder,
  303. receive_timeout=self.master_connection.receive_timeout,
  304. return_empty_attributes=self.master_connection.empty_attributes)
  305. # simulates auto_bind, always with read_server_info=False
  306. if self.master_connection.auto_bind and self.master_connection.auto_bind not in [AUTO_BIND_NONE, AUTO_BIND_DEFAULT]:
  307. if log_enabled(BASIC):
  308. log(BASIC, 'performing automatic bind for <%s>', self.connection)
  309. self.connection.open(read_server_info=False)
  310. if self.master_connection.auto_bind == AUTO_BIND_NO_TLS:
  311. self.connection.bind(read_server_info=False)
  312. elif self.master_connection.auto_bind == AUTO_BIND_TLS_BEFORE_BIND:
  313. self.connection.start_tls(read_server_info=False)
  314. self.connection.bind(read_server_info=False)
  315. elif self.master_connection.auto_bind == AUTO_BIND_TLS_AFTER_BIND:
  316. self.connection.bind(read_server_info=False)
  317. self.connection.start_tls(read_server_info=False)
  318. if self.master_connection.server_pool:
  319. self.connection.server_pool = self.master_connection.server_pool
  320. self.connection.server_pool.initialize(self.connection)
  321. # ReusableStrategy methods
  322. def __init__(self, ldap_connection):
  323. BaseStrategy.__init__(self, ldap_connection)
  324. self.sync = False
  325. self.no_real_dsa = False
  326. self.pooled = True
  327. self.can_stream = False
  328. if hasattr(ldap_connection, 'pool_name') and ldap_connection.pool_name:
  329. self.pool = ReusableStrategy.ConnectionPool(ldap_connection)
  330. else:
  331. if log_enabled(ERROR):
  332. log(ERROR, 'reusable connection must have a pool_name')
  333. raise LDAPConnectionPoolNameIsMandatoryError('reusable connection must have a pool_name')
  334. def open(self, reset_usage=True, read_server_info=True):
  335. # read_server_info not used
  336. self.pool.open_pool = True
  337. self.pool.start_pool()
  338. self.connection.closed = False
  339. if self.connection.usage:
  340. if reset_usage or not self.connection._usage.initial_connection_start_time:
  341. self.connection._usage.start()
  342. def terminate(self):
  343. self.pool.terminate_pool()
  344. self.pool.open_pool = False
  345. self.connection.bound = False
  346. self.connection.closed = True
  347. self.pool.bind_pool = False
  348. self.pool.tls_pool = False
  349. def _close_socket(self):
  350. """
  351. Doesn't really close the socket
  352. """
  353. self.connection.closed = True
  354. if self.connection.usage:
  355. self.connection._usage.closed_sockets += 1
  356. def send(self, message_type, request, controls=None):
  357. if self.pool.started:
  358. if message_type == 'bindRequest':
  359. self.pool.bind_pool = True
  360. counter = BOGUS_BIND
  361. elif message_type == 'unbindRequest':
  362. self.pool.bind_pool = False
  363. counter = BOGUS_UNBIND
  364. elif message_type == 'abandonRequest':
  365. counter = BOGUS_ABANDON
  366. elif message_type == 'extendedReq' and self.connection.starting_tls:
  367. self.pool.tls_pool = True
  368. counter = BOGUS_EXTENDED
  369. else:
  370. with self.pool.pool_lock:
  371. self.pool.counter += 1
  372. if self.pool.counter > LDAP_MAX_INT:
  373. self.pool.counter = 1
  374. counter = self.pool.counter
  375. self.pool.request_queue.put((counter, message_type, request, controls))
  376. return counter
  377. if log_enabled(ERROR):
  378. log(ERROR, 'reusable connection pool not started')
  379. raise LDAPConnectionPoolNotStartedError('reusable connection pool not started')
  380. def validate_bind(self, controls):
  381. # in case of a new connection or different credentials
  382. if (self.connection.user != self.pool.master_connection.user or
  383. self.connection.password != self.pool.master_connection.password or
  384. self.connection.authentication != self.pool.master_connection.authentication or
  385. self.connection.sasl_mechanism != self.pool.master_connection.sasl_mechanism or
  386. self.connection.sasl_credentials != self.pool.master_connection.sasl_credentials):
  387. self.pool.master_connection.user = self.connection.user
  388. self.pool.master_connection.password = self.connection.password
  389. self.pool.master_connection.authentication = self.connection.authentication
  390. self.pool.master_connection.sasl_mechanism = self.connection.sasl_mechanism
  391. self.pool.master_connection.sasl_credentials = self.connection.sasl_credentials
  392. self.pool.rebind_pool()
  393. temp_connection = self.pool.workers[0].connection
  394. old_lazy = temp_connection.lazy
  395. temp_connection.lazy = False
  396. if not self.connection.server.schema or not self.connection.server.info:
  397. result = self.pool.workers[0].connection.bind(controls=controls)
  398. else:
  399. result = self.pool.workers[0].connection.bind(controls=controls, read_server_info=False)
  400. temp_connection.unbind()
  401. temp_connection.lazy = old_lazy
  402. if result:
  403. self.pool.bind_pool = True # bind pool if bind is validated
  404. return result
  405. def get_response(self, counter, timeout=None, get_request=False):
  406. sleeptime = get_config_parameter('RESPONSE_SLEEPTIME')
  407. request=None
  408. if timeout is None:
  409. timeout = get_config_parameter('RESPONSE_WAITING_TIMEOUT')
  410. if counter == BOGUS_BIND: # send a bogus bindResponse
  411. response = list()
  412. result = {'description': 'success', 'referrals': None, 'type': 'bindResponse', 'result': 0, 'dn': '', 'message': '<bogus Bind response>', 'saslCreds': None}
  413. elif counter == BOGUS_UNBIND: # bogus unbind response
  414. response = None
  415. result = None
  416. elif counter == BOGUS_ABANDON: # abandon cannot be executed because of multiple connections
  417. response = list()
  418. result = {'result': 0, 'referrals': None, 'responseName': '1.3.6.1.4.1.1466.20037', 'type': 'extendedResp', 'description': 'success', 'responseValue': 'None', 'dn': '', 'message': '<bogus StartTls response>'}
  419. elif counter == BOGUS_EXTENDED: # bogus startTls extended response
  420. response = list()
  421. result = {'result': 0, 'referrals': None, 'responseName': '1.3.6.1.4.1.1466.20037', 'type': 'extendedResp', 'description': 'success', 'responseValue': 'None', 'dn': '', 'message': '<bogus StartTls response>'}
  422. self.connection.starting_tls = False
  423. else:
  424. response = None
  425. result = None
  426. while timeout >= 0: # waiting for completed message to appear in _incoming
  427. try:
  428. with self.connection.strategy.pool.pool_lock:
  429. response, result, request = self.connection.strategy.pool._incoming.pop(counter)
  430. except KeyError:
  431. sleep(sleeptime)
  432. timeout -= sleeptime
  433. continue
  434. break
  435. if timeout <= 0:
  436. if log_enabled(ERROR):
  437. log(ERROR, 'no response from worker threads in Reusable connection')
  438. raise LDAPResponseTimeoutError('no response from worker threads in Reusable connection')
  439. if isinstance(response, LDAPOperationResult):
  440. raise response # an exception has been raised with raise_exceptions
  441. if get_request:
  442. return response, result, request
  443. return response, result
  444. def post_send_single_response(self, counter):
  445. return counter
  446. def post_send_search(self, counter):
  447. return counter