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.
 
 
 
 

256 regels
13 KiB

  1. """
  2. """
  3. # Created on 2014.03.04
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2019 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
  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. self.connection.start_tls(read_server_info=False)
  143. if message_type != 'bindRequest':
  144. self.connection.bind(read_server_info=False, controls=self._last_bind_controls) # binds with previously used controls unless the request is already a bindRequest
  145. if not self.connection.server.schema and not self.connection.server.info:
  146. self.connection.refresh_server_info()
  147. else:
  148. self.connection._fire_deferred(read_info=False) # in case of lazy connection, not open by the refresh_server_info
  149. except Exception as e:
  150. if log_enabled(ERROR):
  151. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  152. self._add_exception_to_history(type(e)(str(e)))
  153. failure = True
  154. if not failure:
  155. try: # reissuing same operation
  156. ret_value = self.connection.send(message_type, request, controls)
  157. if self.connection.usage:
  158. self.connection._usage.restartable_successes += 1
  159. self._restarting = False
  160. self._reset_exception_history()
  161. return ret_value # successful send
  162. except Exception as e:
  163. if log_enabled(ERROR):
  164. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  165. self._add_exception_to_history(type(e)(str(e)))
  166. failure = True
  167. if failure and self.connection.usage:
  168. self.connection._usage.restartable_failures += 1
  169. if not isinstance(self.restartable_tries, bool):
  170. counter -= 1
  171. self._restarting = False
  172. self.connection.last_error = 'restartable connection failed to send'
  173. if log_enabled(ERROR):
  174. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  175. raise LDAPMaximumRetriesError(self.connection.last_error, self.exception_history, self.restartable_tries)
  176. def post_send_single_response(self, message_id):
  177. try:
  178. ret_value = SyncStrategy.post_send_single_response(self, message_id)
  179. self._reset_exception_history()
  180. return ret_value
  181. except Exception as e:
  182. if log_enabled(ERROR):
  183. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  184. self._add_exception_to_history(type(e)(str(e)))
  185. # if an LDAPExceptionError is raised then resend the request
  186. try:
  187. ret_value = SyncStrategy.post_send_single_response(self, self.send(self._current_message_type, self._current_request, self._current_controls))
  188. self._reset_exception_history()
  189. return ret_value
  190. except Exception as e:
  191. if log_enabled(ERROR):
  192. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  193. self._add_exception_to_history(type(e)(str(e)))
  194. if not isinstance(e, LDAPOperationResult):
  195. self.connection.last_error = 'restartable connection strategy failed in post_send_single_response'
  196. if log_enabled(ERROR):
  197. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  198. raise
  199. def post_send_search(self, message_id):
  200. try:
  201. ret_value = SyncStrategy.post_send_search(self, message_id)
  202. self._reset_exception_history()
  203. return ret_value
  204. except Exception as e:
  205. if log_enabled(ERROR):
  206. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  207. self._add_exception_to_history(type(e)(str(e)))
  208. # if an LDAPExceptionError is raised then resend the request
  209. try:
  210. ret_value = SyncStrategy.post_send_search(self, self.connection.send(self._current_message_type, self._current_request, self._current_controls))
  211. self._reset_exception_history()
  212. return ret_value
  213. except Exception as e:
  214. if log_enabled(ERROR):
  215. log(ERROR, '<%s> while restarting <%s>', e, self.connection)
  216. self._add_exception_to_history(type(e)(str(e)))
  217. if not isinstance(e, LDAPOperationResult):
  218. self.connection.last_error = e.args
  219. if log_enabled(ERROR):
  220. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  221. raise e
  222. def _add_exception_to_history(self, exc):
  223. if not isinstance(self.restartable_tries, bool): # doesn't accumulate when restarting forever
  224. if not isinstance(exc, LDAPMaximumRetriesError): # doesn't add the LDAPMaximumRetriesError exception
  225. self.exception_history.append(exc)
  226. def _reset_exception_history(self):
  227. if self.exception_history:
  228. self.exception_history = []
  229. def get_stream(self):
  230. raise NotImplementedError
  231. def set_stream(self, value):
  232. raise NotImplementedError