Skip to content

Instantly share code, notes, and snippets.

@brianmay
Last active December 20, 2015 02:49
Show Gist options
  • Save brianmay/6059401 to your computer and use it in GitHub Desktop.
Save brianmay/6059401 to your computer and use it in GitHub Desktop.
Test case for LDAP reconnection issue
#!/usr/bin/env python
import ldap
import ldap.modlist
import time
def debug(*argv):
""" print debugging. """
argv = [str(arg) for arg in argv]
print " ".join(argv)
class Connection:
""" LDAP connection """
def __init__(self):
self._obj = None
def _reconnect(self):
""" Try to reconnect """
self._obj = None
debug("connecting")
conn = ldap.initialize('ldap://localhost')
conn.protocol_version = ldap.VERSION3
debug("binding")
conn.simple_bind_s('cn=admin,dc=in,dc=vpac,dc=org', 'password')
        self._obj = conn
def _do_with_retry(self, fn):
# if no connection
if self._obj is None:
# never connected; try to connect and then run fn
debug("initial connection")
self._reconnect()
return fn(self._obj)
# otherwise try to run fn
try:
return fn(self._obj)
except ldap.SERVER_DOWN:
# if it fails, reconnect then retry
debug("SERVER_DOWN, reconnecting")
self._reconnect()
return fn(self._obj)
c = Connection()
i = 0
while True:
try:
r = c._do_with_retry(lambda conn: conn.search_s("cn=admin,dc=in,dc=vpac,dc=org", ldap.SCOPE_BASE))
print r
modlist = []
c._do_with_retry(lambda conn: conn.modify_s("cn=admin,dc=in,dc=vpac,dc=org", modlist))
except Exception as e:
print "Error", e
debug("")
time.sleep(2)
i = i + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment