Create ipaerror module.

Move LDAPError trapping/conversion into the ipaldap module.
Fix xmlrpc layer to encode/decode ipaerrors properly.
Also, implement mid-air collision exception for updates.
This commit is contained in:
Kevin McCarthy 2007-08-22 10:30:51 -07:00
parent a8f302aa9f
commit 7691653c0a
6 changed files with 215 additions and 134 deletions

126
ipa-python/ipaerror.py Normal file
View File

@ -0,0 +1,126 @@
#! /usr/bin/python -E
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 or later
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import exceptions
import types
class IPAError(exceptions.Exception):
"""Base error class for IPA Code"""
def __init__(self, code, message="", detail=None):
"""code is the IPA error code.
message is a human viewable error message.
detail is an optional exception that provides more detail about the
error."""
self.code = code
self.message = message
self.detail = detail
def __str__(self):
return self.message
def __repr__(self):
repr = "%d: %s" % (self.code, self.message)
if self.detail:
repr += "\n%s" % str(self.detail)
return repr
###############
# Error codes #
###############
code_map_dict = {}
def gen_exception(code, message=None, nested_exception=None):
"""This should be used by IPA code to translate error codes into the
correct exception/message to throw.
message is an optional argument which overrides the default message.
nested_exception is an optional argument providing more details
about the error."""
(default_message, exception) = code_map_dict.get(code, ("unknown", IPAError))
if not message:
message = default_message
return exception(code, message, nested_exception)
def exception_for(code):
"""Used to look up the corresponding exception for an error code.
Will usually be used for an except block."""
(default_message, exception) = code_map_dict.get(code, ("unknown", IPAError))
return exception
def gen_error_code(category, detail, message):
"""Private method used to generate exception codes.
category is one of the 16 bit error code category constants.
detail is a 16 bit code within the category.
message is a human readable description on the error.
exception is the exception to throw for this error code."""
code = (category << 16) + detail
exception = types.ClassType("IPAError%d" % code,
(IPAError,),
{})
code_map_dict[code] = (message, exception)
return code
#
# Error codes are broken into two 16-bit values: category and detail
#
#
# LDAP Errors: 0x0001
#
LDAP_CATEGORY = 0x0001
LDAP_DATABASE_ERROR = gen_error_code(
LDAP_CATEGORY,
0x0001,
"A database error occurred")
LDAP_MIDAIR_COLLISION = gen_error_code(
LDAP_CATEGORY,
0x0002,
"Change collided with another change")
LDAP_NOT_FOUND = gen_error_code(
LDAP_CATEGORY,
0x0003,
"Entry not found")
LDAP_DUPLICATE = gen_error_code(
LDAP_CATEGORY,
0x0004,
"Duplicate entry already in LDAP")
LDAP_MISSING_DN = gen_error_code(
LDAP_CATEGORY,
0x0005,
"Entry missing dn")
#
# Input errors (sample - replace me)
#
INPUT_CATEGORY = 0x0002
INPUT_INVALID_ERROR = gen_error_code(
INPUT_CATEGORY,
0x0001,
"Illegal input")

View File

@ -29,6 +29,7 @@ import os
import base64
import user
import ipa
from ipa import ipaerror
# Some errors to catch
# http://cvs.fedora.redhat.com/viewcvs/ldapserver/ldap/servers/plugins/pam_passthru/README?root=dirsec&rev=1.6&view=auto
@ -76,7 +77,7 @@ class RPCClient:
else:
result = server.get_user(username)
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -91,7 +92,7 @@ class RPCClient:
try:
result = server.add_user(user)
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -108,7 +109,7 @@ class RPCClient:
try:
result = server.get_add_schema()
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -121,7 +122,7 @@ class RPCClient:
try:
result = server.get_all_users()
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -138,7 +139,7 @@ class RPCClient:
else:
result = server.find_users(criteria)
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -151,7 +152,7 @@ class RPCClient:
try:
result = server.update_user(olduser, newuser)
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)
@ -164,7 +165,7 @@ class RPCClient:
try:
result = server.mark_user_deleted(uid)
except xmlrpclib.Fault, fault:
raise xmlrpclib.Fault(fault.faultCode, fault.faultString)
raise ipaerror.gen_exception(fault.faultCode, fault.faultString)
except socket.error, (value, msg):
raise xmlrpclib.Fault(value, msg)

View File

@ -17,6 +17,7 @@ import ipa.ipaclient
import ipa.user
import xmlrpclib
import forms.user
from ipa import ipaerror
ipa.config.init_config()
user_new_form = forms.user.UserNewForm()
@ -80,8 +81,8 @@ class Root(controllers.RootController):
rv = client.add_user(new_user)
turbogears.flash("%s added!" % kw['uid'])
raise turbogears.redirect('/usershow', uid=kw['uid'])
except xmlrpclib.Fault, f:
turbogears.flash("User add failed: " + str(f.faultString))
except ipaerror.IPAError, e:
turbogears.flash("User add failed: " + str(e))
return dict(form=user_new_form, tg_template='ipagui.templates.usernew')
@ -129,8 +130,8 @@ class Root(controllers.RootController):
rv = client.update_user(new_user)
turbogears.flash("%s updated!" % kw['uid'])
raise turbogears.redirect('/usershow', uid=kw['uid'])
except xmlrpclib.Fault, f:
turbogears.flash("User update failed: " + str(f.faultString))
except ipaerror.IPAError, e:
turbogears.flash("User update failed: " + str(e))
return dict(form=user_edit_form, user=kw,
tg_template='ipagui.templates.useredit')
@ -143,8 +144,8 @@ class Root(controllers.RootController):
if uid != None and len(uid) > 0:
try:
users = client.find_users(uid.encode('utf-8'))
except xmlrpclib.Fault, f:
turbogears.flash("User show failed: " + str(f.faultString))
except ipaerror.IPAError, e:
turbogears.flash("User show failed: " + str(e))
raise turbogears.redirect("/userlist")
return dict(users=users, fields=forms.user.UserFields())
@ -156,8 +157,8 @@ class Root(controllers.RootController):
try:
user = client.get_user(uid)
return dict(user=user.toDict(), fields=forms.user.UserFields())
except xmlrpclib.Fault, f:
turbogears.flash("User show failed: " + str(f.faultString))
except ipaerror.IPAError, e:
turbogears.flash("User show failed: " + str(e))
raise turbogears.redirect("/")
@validate(form=user_new_form)

View File

@ -39,13 +39,7 @@ from ldap.modlist import modifyModlist
from ldap.ldapobject import SimpleLDAPObject
class Error(Exception): pass
class InvalidArgumentError(Error):
def __init__(self,message): self.message = message
def __repr__(self): return message
class NoSuchEntryError(Error):
def __init__(self,message): self.message = message
def __repr__(self): return message
from ipa import ipaerror
class Entry:
"""This class represents an LDAP Entry object. An LDAP entry consists of a DN
@ -192,12 +186,13 @@ class IPAdmin(SimpleLDAPObject):
instdir = ent.getValue('nsslapd-instancedir')
self.sroot, self.inst = re.match(r'(.*)[\/]slapd-(\w+)$', instdir).groups()
self.errlog = ent.getValue('nsslapd-errorlog')
except (ldap.INSUFFICIENT_ACCESS, ldap.CONNECT_ERROR, NoSuchEntryError):
except (ldap.INSUFFICIENT_ACCESS, ldap.CONNECT_ERROR,
ipaerror.exception_for(ipaerror.LDAP_NOT_FOUND)):
pass # usually means
# print "ignored exception"
except ldap.LDAPError, e:
print "caught exception ", e
raise
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
def __localinit__(self):
SimpleLDAPObject.__init__(self,'ldaps://%s:%d' % (self.host,self.port))
@ -257,18 +252,23 @@ class IPAdmin(SimpleLDAPObject):
def getEntry(self,*args):
"""This wraps the search function. It is common to just get one entry"""
sctrl = self.__get_server_controls__()
if sctrl is not None:
self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
res = self.search(*args)
try:
res = self.search(*args)
# res = self.search_ext(args[0], args[1], filterstr=args[2], attrlist=args[3], serverctrls=sctrl)
# res = self.search_ext(args[0], args[1], filterstr=args[2], attrlist=args[3], serverctrls=sctrl)
except ldap.LDAPError, e:
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
type, obj = self.result(res)
if not obj:
raise NoSuchEntryError("no such entry for " + str(args))
raise ipaerror.gen_exception(ipaerror.LDAP_NOT_FOUND,
"no such entry for " + str(args))
elif isinstance(obj,Entry):
return obj
else: # assume list/tuple
@ -278,14 +278,18 @@ class IPAdmin(SimpleLDAPObject):
"""This wraps the search function to find all users."""
sctrl = self.__get_server_controls__()
if sctrl is not None:
self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
res = self.search(*args)
try:
res = self.search(*args)
except ldap.LDAPError, e:
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
type, obj = self.result(res)
if not obj:
raise NoSuchEntryError("no such entry for " + str(args))
raise ipaerror.gen_exception(ipaerror.LDAP_NOT_FOUND,
"no such entry for " + str(args))
all_users = []
for s in obj:
@ -303,9 +307,9 @@ class IPAdmin(SimpleLDAPObject):
self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
self.add_s(*args)
except ldap.ALREADY_EXISTS:
raise ldap.ALREADY_EXISTS
raise ipaerror.gen_exception(ipaerror.LDAP_DUPLICATE)
except ldap.LDAPError, e:
raise e
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
return "Success"
def updateEntry(self,dn,olduser,newuser):
@ -319,9 +323,13 @@ class IPAdmin(SimpleLDAPObject):
try:
self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
self.modify_s(dn, modlist)
# this is raised when a 'delete' attribute isn't found.
# it indicates the previous attribute was removed by another
# update, making the olduser stale.
except ldap.NO_SUCH_ATTRIBUTE:
raise ipaerror.gen_exception(ipaerror.LDAP_MIDAIR_COLLISION)
except ldap.LDAPError, e:
raise e
# raise Exception, modlist
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
return "Success"
def generateModList(self, old_entry, new_entry):
@ -375,7 +383,7 @@ class IPAdmin(SimpleLDAPObject):
self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl)
self.modify_s(dn, modlist)
except ldap.LDAPError, e:
raise e
raise ipaerror.gen_exception(ipaerror.LDAP_DATABASE_ERROR, None, e)
return "Success"
def __wrapmethods(self):
@ -429,7 +437,8 @@ class IPAdmin(SimpleLDAPObject):
while not entry and int(time.time()) < timeout:
try:
entry = self.getEntry(dn, scope, filter, attrlist)
except NoSuchEntryError: pass # found entry, but no attr
except ipaerror.exception_for(ipaerror.LDAP_NOT_FOUND):
pass # found entry, but no attr
except ldap.NO_SUCH_OBJECT: pass # no entry yet
except ldap.LDAPError, e: # badness
print "\nError reading entry", dn, e

View File

@ -24,10 +24,12 @@ import ldap
import ipaserver.dsinstance
import ipaserver.ipaldap
import ipaserver.util
import string
from types import *
import xmlrpclib
import ipa.config
from ipa import ipaerror
import string
from types import *
import os
import re
@ -83,15 +85,10 @@ class IPAServer:
# FIXME: should we search for this in a specific area of the tree?
filter = "(krbPrincipalName=" + princ + ")"
try:
# The only anonymous search we should have
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,None)
ent = m1.getEntry(self.basedn, self.scope, filter, ['dn'])
_LDAPPool.releaseConn(m1)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
# The only anonymous search we should have
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,None)
ent = m1.getEntry(self.basedn, self.scope, filter, ['dn'])
_LDAPPool.releaseConn(m1)
return "dn:" + ent.dn
@ -153,22 +150,13 @@ class IPAServer:
if (isinstance(username, tuple)):
username = username[0]
try:
dn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
dn = self.get_dn_from_principal(self.princ)
filter = "(uid=" + username + ")"
try:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
ent = m1.getEntry(self.basedn, self.scope, filter, sattrs)
_LDAPPool.releaseConn(m1)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
ent = m1.getEntry(self.basedn, self.scope, filter, sattrs)
_LDAPPool.releaseConn(m1)
return self.convert_entry(ent)
@ -220,22 +208,12 @@ class IPAServer:
if opts:
self.set_principal(opts['remoteuser'])
try:
dn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
dn = self.get_dn_from_principal(self.princ)
try:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
res = m1.addEntry(entry)
_LDAPPool.releaseConn(m1)
return res
except ldap.ALREADY_EXISTS:
raise xmlrpclib.Fault(3, "User already exists")
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, str(e))
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
res = m1.addEntry(entry)
_LDAPPool.releaseConn(m1)
return res
def get_add_schema (self):
"""Get the list of fields to be used when adding users in the GUI."""
@ -290,23 +268,14 @@ class IPAServer:
if opts:
self.set_principal(opts['remoteuser'])
try:
dn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
dn = self.get_dn_from_principal(self.princ)
# FIXME: Is this the filter we want or should it be more specific?
filter = "(objectclass=posixAccount)"
try:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
all_users = m1.getList(self.basedn, self.scope, filter, None)
_LDAPPool.releaseConn(m1)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
all_users = m1.getList(self.basedn, self.scope, filter, None)
_LDAPPool.releaseConn(m1)
users = []
for u in all_users:
@ -338,12 +307,7 @@ class IPAServer:
if opts:
self.set_principal(opts['remoteuser'])
try:
dn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
dn = self.get_dn_from_principal(self.princ)
# TODO: this escaper assumes the python-ldap library will error out
# on invalid codepoints. we need to check malformed utf-8 input
@ -359,12 +323,9 @@ class IPAServer:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,dn)
results = m1.getList(self.basedn, self.scope, filter, sattrs)
_LDAPPool.releaseConn(m1)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
except ipaerror.exception_for(ipaerror.LDAP_NOT_FOUND):
results = []
# raise xmlrpclib.Fault(2, "No such user")
users = []
for u in results:
users.append(self.convert_entry(u))
@ -412,25 +373,17 @@ class IPAServer:
try:
moddn = olduser['dn']
except KeyError, e:
raise xmlrpclib.Fault(4, "Old user has no dn")
raise ipaerror.gen_exception(ipaerror.LDAP_MISSING_DN)
if opts:
self.set_principal(opts['remoteuser'])
try:
proxydn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
proxydn = self.get_dn_from_principal(self.princ)
try:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,proxydn)
res = m1.updateEntry(moddn, olduser, newuser)
_LDAPPool.releaseConn(m1)
return res
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, str(e))
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,proxydn)
res = m1.updateEntry(moddn, olduser, newuser)
_LDAPPool.releaseConn(m1)
return res
def mark_user_deleted (self, args, opts=None):
"""Mark a user as inactive in LDAP. We aren't actually deleting
@ -442,17 +395,9 @@ class IPAServer:
if opts:
self.set_principal(opts['remoteuser'])
try:
proxydn = self.get_dn_from_principal(self.princ)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, e)
except ipaserver.ipaldap.NoSuchEntryError:
raise xmlrpclib.Fault(2, "No such user")
proxydn = self.get_dn_from_principal(self.princ)
try:
user = self.get_user(uid, ['dn', 'nsAccountlock'], opts)
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, str(e))
user = self.get_user(uid, ['dn', 'nsAccountlock'], opts)
# Are we doing an add or replace operation?
if user.has_key('nsaccountlock'):
@ -460,13 +405,10 @@ class IPAServer:
else:
has_key = False
try:
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,proxydn)
res = m1.inactivateEntry(user['dn'], has_key)
_LDAPPool.releaseConn(m1)
return res
except ldap.LDAPError, e:
raise xmlrpclib.Fault(1, str(e))
m1 = _LDAPPool.getConn(self.host,self.port,self.bindca,self.bindcert,self.bindkey,proxydn)
res = m1.inactivateEntry(user['dn'], has_key)
_LDAPPool.releaseConn(m1)
return res
def ldap_search_escape(match):

View File

@ -35,6 +35,8 @@ from mod_python import apache
import ipaserver
import funcs
from ipa import ipaerror
import string
import base64
@ -144,9 +146,9 @@ class ModXMLRPCRequestHandler(object):
# wrap response in a singleton tuple
response = (response,)
response = dumps(response, methodresponse=1, allow_none=1)
except Fault, fault:
except ipaerror.IPAError, e:
self.traceback = True
response = dumps(fault)
response = dumps(Fault(e.code, str(e)))
except:
self.traceback = True
# report exception back to server