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.
 
 
 
 

261 rivejä
13 KiB

  1. """
  2. """
  3. # Created on 2014.03.04
  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 time import sleep
  25. import socket
  26. from .. import get_config_parameter
  27. from .sync import SyncStrategy
  28. from ..core.exceptions import LDAPSocketOpenError, LDAPOperationResult, LDAPMaximumRetriesError, LDAPStartTLSError
  29. from ..utils.log import log, log_enabled, ERROR, BASIC
  30. # noinspection PyBroadException,PyProtectedMember
  31. class RestartableStrategy(SyncStrategy):
  32. def __init__(self, ldap_connection):
  33. SyncStrategy.__init__(self, ldap_connection)
  34. self.sync = True
  35. self.no_real_dsa = False
  36. self.pooled = False
  37. self.can_stream = False
  38. self.restartable_sleep_time = get_config_parameter('RESTARTABLE_SLEEPTIME')
  39. self.restartable_tries = get_config_parameter('RESTARTABLE_TRIES')
  40. self._restarting = False
  41. self._last_bind_controls = None
  42. self._current_message_type = None
  43. self._current_request = None
  44. self._current_controls = None
  45. self._restart_tls = None
  46. self.exception_history = []
  47. def open(self, reset_usage=False, read_server_info=True):
  48. SyncStrategy.open(self, reset_usage, read_server_info)
  49. def _open_socket(self, address, use_ssl=False, unix_socket=False):
  50. """
  51. Try to open and connect a socket to a Server
  52. raise LDAPExceptionError if unable to open or connect socket
  53. if connection is restartable tries for the number of restarting requested or forever
  54. """
  55. try:
  56. SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # try to open socket using SyncWait
  57. self._reset_exception_history()
  58. return
  59. except Exception as e: # machinery for restartable connection
  60. if log_enabled(ERROR):
  61. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  62. self._add_exception_to_history(type(e)(str(e)))
  63. if not self._restarting: # if not already performing a restart
  64. self._restarting = True
  65. counter = self.restartable_tries
  66. while counter > 0: # includes restartable_tries == True
  67. if log_enabled(BASIC):
  68. log(BASIC, 'try #%d to open Restartable connection <%s>', self.restartable_tries - counter, self.connection)
  69. sleep(self.restartable_sleep_time)
  70. if not self.connection.closed:
  71. try: # resetting connection
  72. self.connection.unbind()
  73. except (socket.error, LDAPSocketOpenError): # don't trace catch socket errors because socket could already be closed
  74. pass
  75. except Exception as e:
  76. if log_enabled(ERROR):
  77. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  78. self._add_exception_to_history(type(e)(str(e)))
  79. try: # reissuing same operation
  80. if self.connection.server_pool:
  81. new_server = self.connection.server_pool.get_server(self.connection) # get a server from the server_pool if available
  82. if self.connection.server != new_server:
  83. self.connection.server = new_server
  84. if self.connection.usage:
  85. self.connection._usage.servers_from_pool += 1
  86. SyncStrategy._open_socket(self, address, use_ssl, unix_socket) # calls super (not restartable) _open_socket()
  87. if self.connection.usage:
  88. self.connection._usage.restartable_successes += 1
  89. self.connection.closed = False
  90. self._restarting = False
  91. self._reset_exception_history()
  92. return
  93. except Exception as e:
  94. if log_enabled(ERROR):
  95. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  96. self._add_exception_to_history(type(e)(str(e)))
  97. if self.connection.usage:
  98. self.connection._usage.restartable_failures += 1
  99. if not isinstance(self.restartable_tries, bool):
  100. counter -= 1
  101. self._restarting = False
  102. self.connection.last_error = 'restartable connection strategy failed while opening socket'
  103. if log_enabled(ERROR):
  104. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  105. raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries)
  106. def send(self, message_type, request, controls=None):
  107. self._current_message_type = message_type
  108. self._current_request = request
  109. self._current_controls = controls
  110. if not self._restart_tls: # RFCs doesn't define how to stop tls once started
  111. self._restart_tls = self.connection.tls_started
  112. if message_type == 'bindRequest': # stores controls used in bind operation to be used again when restarting the connection
  113. self._last_bind_controls = controls
  114. try:
  115. message_id = SyncStrategy.send(self, message_type, request, controls) # tries to send using SyncWait
  116. self._reset_exception_history()
  117. return message_id
  118. except Exception as e:
  119. if log_enabled(ERROR):
  120. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  121. self._add_exception_to_history(type(e)(str(e)))
  122. if not self._restarting: # machinery for restartable connection
  123. self._restarting = True
  124. counter = self.restartable_tries
  125. while counter > 0:
  126. if log_enabled(BASIC):
  127. log(BASIC, 'try #%d to send in Restartable connection <%s>', self.restartable_tries - counter, self.connection)
  128. sleep(self.restartable_sleep_time)
  129. if not self.connection.closed:
  130. try: # resetting connection
  131. self.connection.unbind()
  132. except (socket.error, LDAPSocketOpenError): # don't trace socket errors because socket could already be closed
  133. pass
  134. except Exception as e:
  135. if log_enabled(ERROR):
  136. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  137. self._add_exception_to_history(type(e)(str(e)))
  138. failure = False
  139. try: # reopening connection
  140. self.connection.open(reset_usage=False, read_server_info=False)
  141. if self._restart_tls: # restart tls if start_tls was previously used
  142. if not self.connection.start_tls(read_server_info=False):
  143. error = 'restart tls in restartable not successful' + (' - ' + self.connection.last_error if self.connection.last_error else '')
  144. if log_enabled(ERROR):
  145. log(ERROR, '%s for <%s>', error, self)
  146. self.connection.unbind()
  147. raise LDAPStartTLSError(error)
  148. if message_type != 'bindRequest':
  149. self.connection.bind(read_server_info=False, controls=self._last_bind_controls) # binds with previously used controls unless the request is already a bindRequest
  150. if not self.connection.server.schema and not self.connection.server.info:
  151. self.connection.refresh_server_info()
  152. else:
  153. self.connection._fire_deferred(read_info=False) # in case of lazy connection, not open by the refresh_server_info
  154. except Exception as e:
  155. if log_enabled(ERROR):
  156. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  157. self._add_exception_to_history(type(e)(str(e)))
  158. failure = True
  159. if not failure:
  160. try: # reissuing same operation
  161. ret_value = self.connection.send(message_type, request, controls)
  162. if self.connection.usage:
  163. self.connection._usage.restartable_successes += 1
  164. self._restarting = False
  165. self._reset_exception_history()
  166. return ret_value # successful send
  167. except Exception as e:
  168. if log_enabled(ERROR):
  169. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  170. self._add_exception_to_history(type(e)(str(e)))
  171. failure = True
  172. if failure and self.connection.usage:
  173. self.connection._usage.restartable_failures += 1
  174. if not isinstance(self.restartable_tries, bool):
  175. counter -= 1
  176. self._restarting = False
  177. self.connection.last_error = 'restartable connection failed to send'
  178. if log_enabled(ERROR):
  179. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  180. raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries)
  181. def post_send_single_response(self, message_id):
  182. try:
  183. ret_value = SyncStrategy.post_send_single_response(self, message_id)
  184. self._reset_exception_history()
  185. return ret_value
  186. except Exception as e:
  187. if log_enabled(ERROR):
  188. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  189. self._add_exception_to_history(type(e)(str(e)))
  190. # if an LDAPExceptionError is raised then resend the request
  191. try:
  192. ret_value = SyncStrategy.post_send_single_response(self, self.send(self._current_message_type, self._current_request, self._current_controls))
  193. self._reset_exception_history()
  194. return ret_value
  195. except Exception as e:
  196. if log_enabled(ERROR):
  197. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  198. self._add_exception_to_history(type(e)(str(e)))
  199. if not isinstance(e, LDAPOperationResult):
  200. self.connection.last_error = 'restartable connection strategy failed in post_send_single_response'
  201. if log_enabled(ERROR):
  202. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  203. raise
  204. def post_send_search(self, message_id):
  205. try:
  206. ret_value = SyncStrategy.post_send_search(self, message_id)
  207. self._reset_exception_history()
  208. return ret_value
  209. except Exception as e:
  210. if log_enabled(ERROR):
  211. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  212. self._add_exception_to_history(type(e)(str(e)))
  213. # if an LDAPExceptionError is raised then resend the request
  214. try:
  215. ret_value = SyncStrategy.post_send_search(self, self.connection.send(self._current_message_type, self._current_request, self._current_controls))
  216. self._reset_exception_history()
  217. return ret_value
  218. except Exception as e:
  219. if log_enabled(ERROR):
  220. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  221. self._add_exception_to_history(type(e)(str(e)))
  222. if not isinstance(e, LDAPOperationResult):
  223. self.connection.last_error = e.args
  224. if log_enabled(ERROR):
  225. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  226. raise e
  227. def _add_exception_to_history(self, exc):
  228. if not isinstance(self.restartable_tries, bool): # doesn't accumulate when restarting forever
  229. if not isinstance(exc, LDAPMaximumRetriesError): # doesn't add the LDAPMaximumRetriesError exception
  230. self.exception_history.append(exc)
  231. def _reset_exception_history(self):
  232. if self.exception_history:
  233. self.exception_history = []
  234. def get_stream(self):
  235. raise NotImplementedError
  236. def set_stream(self, value):
  237. raise NotImplementedError