Development of an internal social media platform with personalised dashboards for students
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.

reusable.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. """
  2. """
  3. # Created on 2014.03.23
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2018 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_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):
  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. if pool.open_pool and self.worker.connection.closed:
  216. self.worker.connection.open(read_server_info=False)
  217. if pool.tls_pool and not self.worker.connection.tls_started:
  218. self.worker.connection.start_tls(read_server_info=False)
  219. if pool.bind_pool and not self.worker.connection.bound:
  220. self.worker.connection.bind(read_server_info=False)
  221. elif pool.open_pool and not self.worker.connection.closed: # connection already open, issues a start_tls
  222. if pool.tls_pool and not self.worker.connection.tls_started:
  223. self.worker.connection.start_tls(read_server_info=False)
  224. if self.worker.get_info_from_server and counter:
  225. self.worker.connection._fire_deferred()
  226. self.worker.get_info_from_server = False
  227. exc = None
  228. response = None
  229. result = None
  230. try:
  231. if message_type == 'searchRequest':
  232. response = self.worker.connection.post_send_search(self.worker.connection.send(message_type, request, controls))
  233. else:
  234. response = self.worker.connection.post_send_single_response(self.worker.connection.send(message_type, request, controls))
  235. result = self.worker.connection.result
  236. except LDAPOperationResult as e: # raise_exceptions has raised an exception. It must be redirected to the original connection thread
  237. exc = e
  238. with pool.pool_lock:
  239. if exc:
  240. pool._incoming[counter] = (exc, None, None)
  241. else:
  242. pool._incoming[counter] = (response, result, BaseStrategy.decode_request(message_type, request, controls))
  243. self.worker.busy = False
  244. pool.request_queue.task_done()
  245. self.worker.task_counter += 1
  246. if log_enabled(BASIC):
  247. log(BASIC, 'thread terminated')
  248. if self.master_connection.usage:
  249. pool.terminated_usage += self.worker.connection.usage
  250. self.worker.running = False
  251. class PooledConnectionWorker(object):
  252. """
  253. Container for the restartable connection. it includes a thread and a lock to execute the connection in the pool
  254. """
  255. def __init__(self, connection, request_queue):
  256. self.master_connection = connection
  257. self.request_queue = request_queue
  258. self.running = False
  259. self.busy = False
  260. self.get_info_from_server = False
  261. self.connection = None
  262. self.creation_time = None
  263. self.task_counter = 0
  264. self.new_connection()
  265. self.thread = ReusableStrategy.PooledConnectionThread(self, self.master_connection)
  266. self.worker_lock = Lock()
  267. if log_enabled(BASIC):
  268. log(BASIC, 'instantiated PooledConnectionWorker: <%s>', self)
  269. def __str__(self):
  270. s = 'CONN: ' + str(self.connection) + linesep + ' THREAD: '
  271. s += 'running' if self.running else 'halted'
  272. s += ' - ' + ('busy' if self.busy else 'available')
  273. s += ' - ' + ('created at: ' + self.creation_time.isoformat())
  274. s += ' - time to live: ' + str(self.master_connection.strategy.pool.lifetime - (datetime.now() - self.creation_time).seconds)
  275. s += ' - requests served: ' + str(self.task_counter)
  276. return s
  277. def new_connection(self):
  278. from ..core.connection import Connection
  279. # noinspection PyProtectedMember
  280. self.creation_time = datetime.now()
  281. self.connection = Connection(server=self.master_connection.server_pool if self.master_connection.server_pool else self.master_connection.server,
  282. user=self.master_connection.user,
  283. password=self.master_connection.password,
  284. auto_bind=AUTO_BIND_NONE, # do not perform auto_bind because it reads again the schema
  285. version=self.master_connection.version,
  286. authentication=self.master_connection.authentication,
  287. client_strategy=RESTARTABLE,
  288. auto_referrals=self.master_connection.auto_referrals,
  289. auto_range=self.master_connection.auto_range,
  290. sasl_mechanism=self.master_connection.sasl_mechanism,
  291. sasl_credentials=self.master_connection.sasl_credentials,
  292. check_names=self.master_connection.check_names,
  293. collect_usage=self.master_connection._usage,
  294. read_only=self.master_connection.read_only,
  295. raise_exceptions=self.master_connection.raise_exceptions,
  296. lazy=False,
  297. fast_decoder=self.master_connection.fast_decoder,
  298. receive_timeout=self.master_connection.receive_timeout,
  299. return_empty_attributes=self.master_connection.empty_attributes)
  300. # simulates auto_bind, always with read_server_info=False
  301. if self.master_connection.auto_bind and self.master_connection.auto_bind != AUTO_BIND_NONE:
  302. if log_enabled(BASIC):
  303. log(BASIC, 'performing automatic bind for <%s>', self.connection)
  304. self.connection.open(read_server_info=False)
  305. if self.master_connection.auto_bind == AUTO_BIND_NO_TLS:
  306. self.connection.bind(read_server_info=False)
  307. elif self.master_connection.auto_bind == AUTO_BIND_TLS_BEFORE_BIND:
  308. self.connection.start_tls(read_server_info=False)
  309. self.connection.bind(read_server_info=False)
  310. elif self.master_connection.auto_bind == AUTO_BIND_TLS_AFTER_BIND:
  311. self.connection.bind(read_server_info=False)
  312. self.connection.start_tls(read_server_info=False)
  313. if self.master_connection.server_pool:
  314. self.connection.server_pool = self.master_connection.server_pool
  315. self.connection.server_pool.initialize(self.connection)
  316. # ReusableStrategy methods
  317. def __init__(self, ldap_connection):
  318. BaseStrategy.__init__(self, ldap_connection)
  319. self.sync = False
  320. self.no_real_dsa = False
  321. self.pooled = True
  322. self.can_stream = False
  323. if hasattr(ldap_connection, 'pool_name') and ldap_connection.pool_name:
  324. self.pool = ReusableStrategy.ConnectionPool(ldap_connection)
  325. else:
  326. if log_enabled(ERROR):
  327. log(ERROR, 'reusable connection must have a pool_name')
  328. raise LDAPConnectionPoolNameIsMandatoryError('reusable connection must have a pool_name')
  329. def open(self, reset_usage=True, read_server_info=True):
  330. # read_server_info not used
  331. self.pool.open_pool = True
  332. self.pool.start_pool()
  333. self.connection.closed = False
  334. if self.connection.usage:
  335. if reset_usage or not self.connection._usage.initial_connection_start_time:
  336. self.connection._usage.start()
  337. def terminate(self):
  338. self.pool.terminate_pool()
  339. self.pool.open_pool = False
  340. self.connection.bound = False
  341. self.connection.closed = True
  342. self.pool.bind_pool = False
  343. self.pool.tls_pool = False
  344. def _close_socket(self):
  345. """
  346. Doesn't really close the socket
  347. """
  348. self.connection.closed = True
  349. if self.connection.usage:
  350. self.connection._usage.closed_sockets += 1
  351. def send(self, message_type, request, controls=None):
  352. if self.pool.started:
  353. if message_type == 'bindRequest':
  354. self.pool.bind_pool = True
  355. counter = BOGUS_BIND
  356. elif message_type == 'unbindRequest':
  357. self.pool.bind_pool = False
  358. counter = BOGUS_UNBIND
  359. elif message_type == 'abandonRequest':
  360. counter = BOGUS_ABANDON
  361. elif message_type == 'extendedReq' and self.connection.starting_tls:
  362. self.pool.tls_pool = True
  363. counter = BOGUS_EXTENDED
  364. else:
  365. with self.pool.pool_lock:
  366. self.pool.counter += 1
  367. if self.pool.counter > LDAP_MAX_INT:
  368. self.pool.counter = 1
  369. counter = self.pool.counter
  370. self.pool.request_queue.put((counter, message_type, request, controls))
  371. return counter
  372. if log_enabled(ERROR):
  373. log(ERROR, 'reusable connection pool not started')
  374. raise LDAPConnectionPoolNotStartedError('reusable connection pool not started')
  375. def validate_bind(self, controls):
  376. # in case of a new connection or different credentials
  377. if (self.connection.user != self.pool.master_connection.user or
  378. self.connection.password != self.pool.master_connection.password or
  379. self.connection.authentication != self.pool.master_connection.authentication or
  380. self.connection.sasl_mechanism != self.pool.master_connection.sasl_mechanism or
  381. self.connection.sasl_credentials != self.pool.master_connection.sasl_credentials):
  382. self.pool.master_connection.user = self.connection.user
  383. self.pool.master_connection.password = self.connection.password
  384. self.pool.master_connection.authentication = self.connection.authentication
  385. self.pool.master_connection.sasl_mechanism = self.connection.sasl_mechanism
  386. self.pool.master_connection.sasl_credentials = self.connection.sasl_credentials
  387. self.pool.rebind_pool()
  388. temp_connection = self.pool.workers[0].connection
  389. temp_connection.lazy = False
  390. if not self.connection.server.schema or not self.connection.server.info:
  391. result = self.pool.workers[0].connection.bind(controls=controls)
  392. else:
  393. result = self.pool.workers[0].connection.bind(controls=controls, read_server_info=False)
  394. temp_connection.unbind()
  395. temp_connection.lazy = True
  396. if result:
  397. self.pool.bind_pool = True # bind pool if bind is validated
  398. return result
  399. def get_response(self, counter, timeout=None, get_request=False):
  400. sleeptime = get_config_parameter('RESPONSE_SLEEPTIME')
  401. request=None
  402. if timeout is None:
  403. timeout = get_config_parameter('RESPONSE_WAITING_TIMEOUT')
  404. if counter == BOGUS_BIND: # send a bogus bindResponse
  405. response = list()
  406. result = {'description': 'success', 'referrals': None, 'type': 'bindResponse', 'result': 0, 'dn': '', 'message': '<bogus Bind response>', 'saslCreds': None}
  407. elif counter == BOGUS_UNBIND: # bogus unbind response
  408. response = None
  409. result = None
  410. elif counter == BOGUS_ABANDON: # abandon cannot be executed because of multiple connections
  411. response = list()
  412. 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>'}
  413. elif counter == BOGUS_EXTENDED: # bogus startTls extended response
  414. response = list()
  415. 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>'}
  416. self.connection.starting_tls = False
  417. else:
  418. response = None
  419. result = None
  420. while timeout >= 0: # waiting for completed message to appear in _incoming
  421. try:
  422. with self.connection.strategy.pool.pool_lock:
  423. response, result, request = self.connection.strategy.pool._incoming.pop(counter)
  424. except KeyError:
  425. sleep(sleeptime)
  426. timeout -= sleeptime
  427. continue
  428. break
  429. if timeout <= 0:
  430. if log_enabled(ERROR):
  431. log(ERROR, 'no response from worker threads in Reusable connection')
  432. raise LDAPResponseTimeoutError('no response from worker threads in Reusable connection')
  433. if isinstance(response, LDAPOperationResult):
  434. raise response # an exception has been raised with raise_exceptions
  435. if get_request:
  436. return response, result, request
  437. return response, result
  438. def post_send_single_response(self, counter):
  439. return counter
  440. def post_send_search(self, counter):
  441. return counter