LdapServer : Review logging and exception handling

This commit is contained in:
Benjamin Renard 2014-06-25 19:16:18 +02:00
parent 9ba2a43a04
commit 8b874b7633

View file

@ -1,6 +1,5 @@
#!/usr/bin/python #!/usr/bin/python
import sys
import ldap import ldap
import ldap.modlist as modlist import ldap.modlist as modlist
import logging import logging
@ -14,13 +13,20 @@ class LdapServer(object):
con = 0 con = 0
def __init__(self,uri,dn=None,pwd=None,v2=None): def __init__(self,uri,dn=None,pwd=None,v2=None,raiseOnError=False):
self.uri = uri self.uri = uri
self.dn = dn self.dn = dn
self.pwd = pwd self.pwd = pwd
self.raiseOnError = raiseOnError
if v2: if v2:
self.v2=True self.v2=True
def _error(self,error,level=logging.WARNING):
if self.raiseOnError:
raise 'LdapServer - Error connecting and binding to LDAP server : %s' % e
else:
logging.log(level,error)
def connect(self): def connect(self):
if self.con == 0: if self.con == 0:
try: try:
@ -34,9 +40,11 @@ class LdapServer(object):
con.simple_bind_s(self.dn,self.pwd) con.simple_bind_s(self.dn,self.pwd)
self.con = con self.con = con
return True
except ldap.LDAPError, e: except ldap.LDAPError, e:
logging.critical('LdapServer - Error connecting and binding to LDAP server : %s' % e) self._error('LdapServer - Error connecting and binding to LDAP server : %s' % e,logging.CRITICAL)
sys.exit(1) return False
return True
def search(self,basedn,filter,attrs,sizelimit=0): def search(self,basedn,filter,attrs,sizelimit=0):
res_id = self.con.search(basedn,ldap.SCOPE_SUBTREE,filter,attrs) res_id = self.con.search(basedn,ldap.SCOPE_SUBTREE,filter,attrs)
@ -59,21 +67,19 @@ class LdapServer(object):
self.con.add_s(dn,ldif) self.con.add_s(dn,ldif)
return True return True
except ldap.LDAPError, e: except ldap.LDAPError, e:
logging.warning("LdapServer - Error adding %s : %s" % (dn,e)) self._error("LdapServer - Error adding %s : %s" % (dn,e))
return False return False
def update_object(self,dn,old,new): def update_object(self,dn,old,new):
ldif = modlist.modifyModlist(old,new) ldif = modlist.modifyModlist(old,new)
if ldif == []: if ldif == []:
#logging.debug("LdapServer - No change for %s" % dn)
return True return True
try: try:
#logging.debug("LdapServer - Update %s" % dn)
self.con.modify_s(dn,ldif) self.con.modify_s(dn,ldif)
return True return True
except ldap.LDAPError, e: except ldap.LDAPError, e:
logging.warning("LdapServer - Error updating %s : %s" % (dn,e)) self._error("LdapServer - Error updating %s : %s" % (dn,e))
return False return False
def drop_object(self,dn): def drop_object(self,dn):
@ -82,7 +88,7 @@ class LdapServer(object):
self.con.delete_s(dn) self.con.delete_s(dn)
return True return True
except ldap.LDAPError, e: except ldap.LDAPError, e:
logging.warning("LdapServer - Error deleting %s : %s" % (dn,e)) self._error("LdapServer - Error deleting %s : %s" % (dn,e))
return False return False