Remove some uses of raw python-ldap

Part of the work for: https://fedorahosted.org/freeipa/ticket/2660
This commit is contained in:
Petr Viktorin 2013-01-30 09:51:08 -05:00 committed by Martin Kosek
parent 29a02a3530
commit 982b782777
9 changed files with 140 additions and 199 deletions

View File

@ -22,7 +22,7 @@
import sys import sys
import os import os
import ldap, krbV import krbV
from ipapython.ipa_log_manager import * from ipapython.ipa_log_manager import *
from ipapython import ipautil from ipapython import ipautil
@ -48,17 +48,6 @@ commands = {
"force-sync":(0, 0, "", "") "force-sync":(0, 0, "", "")
} }
def convert_error(exc):
"""
LDAP exceptions are a dictionary, make them prettier.
"""
if isinstance(exc, ldap.LDAPError):
desc = exc.args[0]['desc'].strip()
info = exc.args[0].get('info', '').strip()
return '%s %s' % (desc, info)
else:
return str(exc)
def get_cs_replication_manager(realm, host, dirman_passwd): def get_cs_replication_manager(realm, host, dirman_passwd):
"""Get a CSReplicationManager for a remote host """Get a CSReplicationManager for a remote host
@ -145,14 +134,14 @@ class CSReplicationManager(replication.ReplicationManager):
def delete_referral(self, hostname, port): def delete_referral(self, hostname, port):
dn = DN(('cn', self.suffix), ('cn', 'mapping tree'), ('cn', 'config')) dn = DN(('cn', self.suffix), ('cn', 'mapping tree'), ('cn', 'config'))
# TODO: should we detect proto somehow ? entry = self.conn.get_entry(dn)
mod = [(ldap.MOD_DELETE, 'nsslapd-referral',
'ldap://%s/%s' % (ipautil.format_netloc(hostname, port), self.suffix))]
try: try:
self.conn.modify_s(dn, mod) # TODO: should we detect proto somehow ?
entry['nsslapd-referral'].remove('ldap://%s/%s' %
(ipautil.format_netloc(hostname, port), self.suffix))
self.conn.update_entry(entry)
except Exception, e: except Exception, e:
root_logger.debug("Failed to remove referral value: %s" % convert_error(e)) root_logger.debug("Failed to remove referral value: %s" % e)
def has_ipaca(self): def has_ipaca(self):
try: try:
@ -211,7 +200,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
conn.do_simple_bind(bindpw=dirman_passwd) conn.do_simple_bind(bindpw=dirman_passwd)
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm)) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
entries = conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
for ent in entries: for ent in entries:
try: try:
@ -222,7 +211,9 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
peers[ent.single_value('cn')] = ['CA not configured', ''] peers[ent.single_value('cn')] = ['CA not configured', '']
except Exception, e: except Exception, e:
sys.exit("Failed to get data from '%s' while trying to list replicas: %s" % (host, convert_error(e))) sys.exit(
"Failed to get data from '%s' while trying to list replicas: %s" %
(host, e))
finally: finally:
conn.unbind() conn.unbind()
@ -272,10 +263,10 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl1.hostnames = [replica1, replica2] repl1.hostnames = [replica1, replica2]
except ldap.SERVER_DOWN, e: except errors.NetworkError, e:
sys.exit("Unable to connect to %s: %s" % (replica1, convert_error(e))) sys.exit("Unable to connect to %s: %s" % (replica1, e))
except Exception, e: except Exception, e:
sys.exit("Failed to get data from '%s': %s" % (replica1, convert_error(e))) sys.exit("Failed to get data from '%s': %s" % (replica1, e))
try: try:
repl2 = get_cs_replication_manager(realm, replica2, dirman_passwd) repl2 = get_cs_replication_manager(realm, replica2, dirman_passwd)
@ -307,16 +298,12 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
if replica2_dn is None: if replica2_dn is None:
sys.exit("'%s' has no replication agreement for '%s'" % (replica1, replica2)) sys.exit("'%s' has no replication agreement for '%s'" % (replica1, replica2))
except ldap.NO_SUCH_OBJECT:
print "'%s' has no replication agreement for '%s'" % (replica2, replica1)
if not force:
sys.exit(1)
except errors.NotFound: except errors.NotFound:
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print "'%s' has no replication agreement for '%s'" % (replica2, replica1)
if not force: if not force:
return return
except Exception, e: except Exception, e:
print "Failed to get data from '%s': %s" % (replica2, convert_error(e)) print "Failed to get data from '%s': %s" % (replica2, e)
if not force: if not force:
sys.exit(1) sys.exit(1)
@ -326,7 +313,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl2.delete_agreement(replica1, replica2_dn) repl2.delete_agreement(replica1, replica2_dn)
repl2.delete_referral(replica1, repl1.port) repl2.delete_referral(replica1, repl1.port)
except Exception, e: except Exception, e:
print "Unable to remove agreement on %s: %s" % (replica2, convert_error(e)) print "Unable to remove agreement on %s: %s" % (replica2, e)
failed = True failed = True
if failed: if failed:
@ -354,7 +341,7 @@ def del_master(realm, hostname, options):
thisrepl = get_cs_replication_manager(realm, options.host, thisrepl = get_cs_replication_manager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception, e:
sys.exit("Failed to connect to server %s: %s" % (options.host, convert_error(e))) sys.exit("Failed to connect to server %s: %s" % (options.host, e))
# 2. Ensure we have an agreement with the master # 2. Ensure we have an agreement with the master
if thisrepl.get_replication_agreement(hostname) is None: if thisrepl.get_replication_agreement(hostname) is None:
@ -366,7 +353,7 @@ def del_master(realm, hostname, options):
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception, e:
if not options.force: if not options.force:
print "Unable to delete replica %s: %s" % (hostname, convert_error(e)) print "Unable to delete replica %s: %s" % (hostname, e)
sys.exit(1) sys.exit(1)
else: else:
print "Unable to connect to replica %s, forcing removal" % hostname print "Unable to connect to replica %s, forcing removal" % hostname
@ -384,7 +371,7 @@ def del_master(realm, hostname, options):
try: try:
del_link(realm, r, hostname, options.dirman_passwd, force=True) del_link(realm, r, hostname, options.dirman_passwd, force=True)
except Exception, e: except Exception, e:
sys.exit("There were issues removing a connection: %s" % convert_error(e)) sys.exit("There were issues removing a connection: %s" % e)
def add_link(realm, replica1, replica2, dirman_passwd, options): def add_link(realm, replica1, replica2, dirman_passwd, options):
repl2 = get_cs_replication_manager(realm, replica2, dirman_passwd) repl2 = get_cs_replication_manager(realm, replica2, dirman_passwd)
@ -394,7 +381,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
dn = DN(('cn', 'CA'), ('cn', replica2), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), dn = DN(('cn', 'CA'), ('cn', replica2), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'),
ipautil.realm_to_suffix(realm)) ipautil.realm_to_suffix(realm))
conn.get_entries(dn, ldap.SCOPE_ONELEVEL) conn.get_entries(dn, conn.SCOPE_ONELEVEL)
conn.unbind() conn.unbind()
except errors.NotFound: except errors.NotFound:
sys.exit('%s does not have a CA configured.' % replica2) sys.exit('%s does not have a CA configured.' % replica2)
@ -411,12 +398,14 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
sys.exit('This replication agreement already exists.') sys.exit('This replication agreement already exists.')
repl1.hostnames = [replica1, replica2] repl1.hostnames = [replica1, replica2]
except ldap.NO_SUCH_OBJECT: except errors.NotFound:
sys.exit("Cannot find replica '%s'" % replica1) sys.exit("Cannot find replica '%s'" % replica1)
except ldap.SERVER_DOWN, e: except errors.NetworkError, e:
sys.exit("Unable to connect to %s: %s" % (replica1, convert_error(e))) sys.exit("Unable to connect to %s: %s" % (replica1, e))
except Exception, e: except Exception, e:
sys.exit("Failed to get data from '%s' while trying to get current agreements: %s" % (replica1, convert_error(e))) sys.exit(
"Failed to get data from '%s' while trying to get current "
"agreements: %s" % (replica1, e))
repl1.setup_replication( repl1.setup_replication(
replica2, repl2.port, 0, DN(('cn', 'Directory Manager')), replica2, repl2.port, 0, DN(('cn', 'Directory Manager')),
@ -436,7 +425,7 @@ def re_initialize(realm, options):
filter = repl.get_agreement_filter(host=thishost) filter = repl.get_agreement_filter(host=thishost)
try: try:
entry = repl.conn.get_entries( entry = repl.conn.get_entries(
DN(('cn', 'config')), ldap.SCOPE_SUBTREE, filter) DN(('cn', 'config')), repl.conn.SCOPE_SUBTREE, filter)
except errors.NotFound: except errors.NotFound:
root_logger.error("Unable to find %s -> %s replication agreement" % (options.fromhost, thishost)) root_logger.error("Unable to find %s -> %s replication agreement" % (options.fromhost, thishost))
sys.exit(1) sys.exit(1)
@ -452,7 +441,7 @@ def force_sync(realm, thishost, fromhost, dirman_passwd):
try: try:
repl.force_sync(repl.conn, thishost) repl.force_sync(repl.conn, thishost)
except Exception, e: except Exception, e:
sys.exit(convert_error(e)) sys.exit(e)
def main(): def main():
options, args = parse_options() options, args = parse_options()
@ -525,13 +514,5 @@ except KeyboardInterrupt:
sys.exit(1) sys.exit(1)
except SystemExit, e: except SystemExit, e:
sys.exit(e) sys.exit(e)
except ldap.INVALID_CREDENTIALS:
sys.exit("Invalid password")
except ldap.INSUFFICIENT_ACCESS:
sys.exit("Insufficient access")
except ldap.LOCAL_ERROR, e:
sys.exit(convert_error(e))
except ldap.SERVER_DOWN, e:
sys.exit("%s" % convert_error(e))
except Exception, e: except Exception, e:
sys.exit("unexpected error: %s" % convert_error(e)) sys.exit("unexpected error: %s" % e)

View File

@ -19,6 +19,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from optparse import OptionGroup, SUPPRESS_HELP
import krbV
from ipaserver.install import service, bindinstance, ntpinstance, httpinstance from ipaserver.install import service, bindinstance, ntpinstance, httpinstance
from ipaserver.install.installutils import * from ipaserver.install.installutils import *
from ipaserver.install import installutils from ipaserver.install import installutils
@ -26,10 +30,7 @@ from ipapython import version
from ipapython import ipautil, sysrestore from ipapython import ipautil, sysrestore
from ipalib import api, errors, util from ipalib import api, errors, util
from ipapython.config import IPAOptionParser from ipapython.config import IPAOptionParser
from optparse import OptionGroup, SUPPRESS_HELP from ipapython.ipa_log_manager import standard_logging_setup, root_logger
import krbV
import ldap
from ipapython.ipa_log_manager import *
log_file_name = "/var/log/ipaserver-install.log" log_file_name = "/var/log/ipaserver-install.log"
@ -148,7 +149,7 @@ def main():
try: try:
bind.ldap_connect() bind.ldap_connect()
bind.ldap_disconnect() bind.ldap_disconnect()
except ldap.INVALID_CREDENTIALS, e: except errors.ACIError:
sys.exit("Password is not valid!") sys.exit("Password is not valid!")
# Check we have a public IP that is associated with the hostname # Check we have a public IP that is associated with the hostname

View File

@ -18,26 +18,16 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import ldap
import re import re
import sys import sys
try: from optparse import OptionParser
from optparse import OptionParser
from ipapython import ipautil, config
from ipaserver.install import installutils
from ipaserver import ipaldap
from ipalib import api, errors
from ipapython.ipa_log_manager import *
from ipapython.dn import DN
except ImportError: from ipapython import ipautil, config
print >> sys.stderr, """\ from ipaserver.install import installutils
There was a problem importing one of the required Python modules. The from ipaserver import ipaldap
error was: from ipalib import api, errors
from ipapython.ipa_log_manager import *
%s from ipapython.dn import DN
""" % sys.exc_value
sys.exit(1)
CACERT = "/etc/ipa/ca.crt" CACERT = "/etc/ipa/ca.crt"
@ -103,28 +93,24 @@ def main():
conn.do_simple_bind(bindpw=options.dirman_password) conn.do_simple_bind(bindpw=options.dirman_password)
else: else:
conn.do_sasl_gssapi_bind() conn.do_sasl_gssapi_bind()
except ldap.LOCAL_ERROR: except errors.ACIError:
dirman_password = get_dirman_password() dirman_password = get_dirman_password()
if dirman_password is None: if dirman_password is None:
sys.exit("\nDirectory Manager password required") sys.exit("\nDirectory Manager password required")
try: try:
conn.do_simple_bind(bindpw=dirman_password) conn.do_simple_bind(bindpw=dirman_password)
except ldap.INVALID_CREDENTIALS: except errors.ACIError:
sys.exit("Invalid credentials") sys.exit("Invalid credentials")
except ldap.INVALID_CREDENTIALS:
sys.exit("Invalid credentials")
except errors.ExecutionError, lde: except errors.ExecutionError, lde:
sys.exit("An error occurred while connecting to the server.\n%s\n" % sys.exit("An error occurred while connecting to the server.\n%s\n" %
str(lde)) str(lde))
except errors.ACIError, e:
sys.exit("Authentication failed: %s" % e.info)
if options.list_managed_entries: if options.list_managed_entries:
# List available Managed Entry Plugins # List available Managed Entry Plugins
managed_entries = None managed_entries = None
try: try:
entries = conn.get_entries( entries = conn.get_entries(
managed_entry_definitions_dn, ldap.SCOPE_SUBTREE, filter) managed_entry_definitions_dn, conn.SCOPE_SUBTREE, filter)
except Exception, e: except Exception, e:
root_logger.debug("Search for managed entries failed: %s" % str(e)) root_logger.debug("Search for managed entries failed: %s" % str(e))
sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn) sys.exit("Unable to find managed entries at %s" % managed_entry_definitions_dn)
@ -143,7 +129,7 @@ def main():
disabled = True disabled = True
try: try:
[entry] = conn.get_entries(def_dn, ldap.SCOPE_BASE, [entry] = conn.get_entries(def_dn, conn.SCOPE_BASE,
filter, ['originfilter']) filter, ['originfilter'])
disable_attr = '(objectclass=disable)' disable_attr = '(objectclass=disable)'
try: try:
@ -151,8 +137,6 @@ def main():
disabled = re.search(r'%s' % disable_attr, org_filter) disabled = re.search(r'%s' % disable_attr, org_filter)
except KeyError: except KeyError:
sys.exit("%s is not a valid Managed Entry" % def_dn) sys.exit("%s is not a valid Managed Entry" % def_dn)
except ldap.NO_SUCH_OBJECT:
sys.exit("%s is not a valid Managed Entry" % def_dn)
except errors.NotFound: except errors.NotFound:
sys.exit("%s is not a valid Managed Entry" % def_dn) sys.exit("%s is not a valid Managed Entry" % def_dn)
except errors.ExecutionError, lde: except errors.ExecutionError, lde:
@ -175,12 +159,8 @@ def main():
# Remove disable_attr from filter # Remove disable_attr from filter
enable_attr = org_filter.replace(disable_attr, '') enable_attr = org_filter.replace(disable_attr, '')
#enable_attr = {'originfilter': enable_attr} #enable_attr = {'originfilter': enable_attr}
conn.modify_s( entry['originfilter'] = [enable_attr]
def_dn, conn.update_entry(entry)
[(ldap.MOD_REPLACE,
'originfilter',
enable_attr)]
)
print "Enabling Plugin" print "Enabling Plugin"
retval = 0 retval = 0
except errors.NotFound: except errors.NotFound:
@ -203,12 +183,8 @@ def main():
disable_attr = org_filter[:2] + disable_attr + org_filter[2:] disable_attr = org_filter[:2] + disable_attr + org_filter[2:]
else: else:
disable_attr = '(&%s(%s))' % (disable_attr, org_filter) disable_attr = '(&%s(%s))' % (disable_attr, org_filter)
conn.modify_s( entry['originfilter'] = [disable_attr]
def_dn, conn.update_entry(entry)
[(ldap.MOD_REPLACE,
'originfilter',
disable_attr)]
)
print "Disabling Plugin" print "Disabling Plugin"
except errors.NotFound: except errors.NotFound:
print "Plugin is already disabled" print "Plugin is already disabled"

View File

@ -20,7 +20,7 @@
import sys import sys
import os import os
import ldap, re, krbV import re, krbV
import traceback import traceback
from urllib2 import urlparse from urllib2 import urlparse
@ -54,16 +54,6 @@ commands = {
"list-clean-ruv":(0, 0, "", ""), "list-clean-ruv":(0, 0, "", ""),
} }
def convert_error(exc):
"""
LDAP exceptions are a dictionary, make them prettier.
"""
if isinstance(exc, ldap.LDAPError):
desc = exc.args[0]['desc'].strip()
info = exc.args[0].get('info', '').strip()
return '%s %s' % (desc, info)
else:
return str(exc)
def parse_options(): def parse_options():
parser = IPAOptionParser(version=version.VERSION) parser = IPAOptionParser(version=version.VERSION)
@ -128,7 +118,7 @@ def test_connection(realm, host):
ents = replman.find_replication_agreements() ents = replman.find_replication_agreements()
del replman del replman
return True return True
except ldap.LOCAL_ERROR: except errors.ACIError:
return False return False
except errors.NotFound: except errors.NotFound:
# We do a search in cn=config. NotFound in this case means no # We do a search in cn=config. NotFound in this case means no
@ -156,7 +146,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm)) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
try: try:
entries = conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
except: except:
print "Failed to read master data from '%s': %s" % (host, str(e)) print "Failed to read master data from '%s': %s" % (host, str(e))
return return
@ -166,7 +156,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
dn = DN(('cn', 'replicas'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm)) dn = DN(('cn', 'replicas'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
try: try:
entries = conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = conn.get_entries(dn, conn.SCOPE_ONELEVEL)
except: except:
pass pass
else: else:
@ -196,7 +186,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
dirman_passwd) dirman_passwd)
cn, dn = repl.agreement_dn(replica) cn, dn = repl.agreement_dn(replica)
entries = repl.conn.get_entries( entries = repl.conn.get_entries(
dn, ldap.SCOPE_BASE, dn, conn.SCOPE_BASE,
"(objectclass=nsDSWindowsReplicationAgreement)") "(objectclass=nsDSWindowsReplicationAgreement)")
ent_type = 'winsync' ent_type = 'winsync'
else: else:
@ -205,7 +195,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
entries = repl.find_replication_agreements() entries = repl.find_replication_agreements()
ent_type = 'replica' ent_type = 'replica'
except Exception, e: except Exception, e:
print "Failed to get data from '%s': %s" % (replica, convert_error(e)) print "Failed to get data from '%s': %s" % (replica, e)
return return
for entry in entries: for entry in entries:
@ -249,11 +239,11 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
print "Please use the 'del' command to remove it from the domain" print "Please use the 'del' command to remove it from the domain"
return False return False
except (ldap.NO_SUCH_OBJECT, errors.NotFound): except errors.NotFound:
print "'%s' has no replication agreement for '%s'" % (replica1, replica2) print "'%s' has no replication agreement for '%s'" % (replica1, replica2)
return False return False
except Exception, e: except Exception, e:
print "Failed to determine agreement type for '%s': %s" % (replica1, convert_error(e)) print "Failed to determine agreement type for '%s': %s" % (replica1, e)
return False return False
if type1 == replication.IPA_REPLICA: if type1 == replication.IPA_REPLICA:
@ -266,12 +256,12 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
print "Please use the 'del' command to remove it from the domain" print "Please use the 'del' command to remove it from the domain"
return False return False
except (ldap.NO_SUCH_OBJECT, errors.NotFound): except errors.NotFound:
print "'%s' has no replication agreement for '%s'" % (replica2, replica1) print "'%s' has no replication agreement for '%s'" % (replica2, replica1)
if not force: if not force:
return False return False
except Exception, e: except Exception, e:
print "Failed to get list of agreements from '%s': %s" % (replica2, convert_error(e)) print "Failed to get list of agreements from '%s': %s" % (replica2, e)
if not force: if not force:
return False return False
@ -286,7 +276,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
repl2.delete_referral(replica1) repl2.delete_referral(replica1)
repl2.set_readonly(readonly=False) repl2.set_readonly(readonly=False)
except Exception, e: except Exception, e:
print "Unable to remove agreement on %s: %s" % (replica2, convert_error(e)) print "Unable to remove agreement on %s: %s" % (replica2, e)
failed = True failed = True
if failed: if failed:
@ -305,13 +295,13 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
try: try:
dn = DN(('cn', replica2), ('cn', 'replicas'), ('cn', 'ipa'), ('cn', 'etc'), dn = DN(('cn', replica2), ('cn', 'replicas'), ('cn', 'ipa'), ('cn', 'etc'),
ipautil.realm_to_suffix(realm)) ipautil.realm_to_suffix(realm))
entries = repl1.conn.get_entries(dn, ldap.SCOPE_SUBTREE) entries = repl1.conn.get_entries(dn, repl1.conn.SCOPE_SUBTREE)
if entries: if entries:
entries.sort(key=len, reverse=True) entries.sort(key=len, reverse=True)
for entry in entries: for entry in entries:
repl1.conn.delete_entry(entry) repl1.conn.delete_entry(entry)
except Exception, e: except Exception, e:
print "Error deleting winsync replica shared info: %s" % convert_error(e) print "Error deleting winsync replica shared info: %s" % e
print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2) print "Deleted replication agreement from '%s' to '%s'" % (replica1, replica2)
@ -327,13 +317,14 @@ def get_ruv(realm, host, dirman_passwd):
try: try:
thisrepl = replication.ReplicationManager(realm, host, dirman_passwd) thisrepl = replication.ReplicationManager(realm, host, dirman_passwd)
except Exception, e: except Exception, e:
print "Failed to connect to server %s: %s" % (host, convert_error(e)) print "Failed to connect to server %s: %s" % (host, e)
sys.exit(1) sys.exit(1)
search_filter = '(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))' search_filter = '(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))'
try: try:
entries = thisrepl.conn.get_entries( entries = thisrepl.conn.get_entries(
api.env.basedn, ldap.SCOPE_ONELEVEL, search_filter, ['nsds50ruv']) api.env.basedn, thisrepl.conn.SCOPE_ONELEVEL, search_filter,
['nsds50ruv'])
except errors.NotFound: except errors.NotFound:
print "No RUV records found." print "No RUV records found."
sys.exit(0) sys.exit(0)
@ -456,7 +447,7 @@ def list_clean_ruv(realm, host, dirman_passwd, verbose):
repl = replication.ReplicationManager(realm, host, dirman_passwd) repl = replication.ReplicationManager(realm, host, dirman_passwd)
dn = DN(('cn', 'cleanallruv'),('cn', 'tasks'), ('cn', 'config')) dn = DN(('cn', 'cleanallruv'),('cn', 'tasks'), ('cn', 'config'))
try: try:
entries = repl.conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL)
except errors.NotFound: except errors.NotFound:
print "No CLEANALLRUV tasks running" print "No CLEANALLRUV tasks running"
else: else:
@ -473,7 +464,7 @@ def list_clean_ruv(realm, host, dirman_passwd, verbose):
dn = DN(('cn', 'abort cleanallruv'),('cn', 'tasks'), ('cn', 'config')) dn = DN(('cn', 'abort cleanallruv'),('cn', 'tasks'), ('cn', 'config'))
try: try:
entries = repl.conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = repl.conn.get_entries(dn, repl.conn.SCOPE_ONELEVEL)
except errors.NotFound: except errors.NotFound:
print "No abort CLEANALLRUV tasks running" print "No abort CLEANALLRUV tasks running"
else: else:
@ -514,7 +505,7 @@ def check_last_link(delrepl, realm, dirman_passwd, force):
for replica in replica_names: for replica in replica_names:
try: try:
repl = replication.ReplicationManager(realm, replica, dirman_passwd) repl = replication.ReplicationManager(realm, replica, dirman_passwd)
except ldap.SERVER_DOWN, e: except errors.NetworkError:
print "Unable to validate that '%s' will not be orphaned." % replica print "Unable to validate that '%s' will not be orphaned." % replica
if not force and not ipautil.user_input("Continue to delete?", False): if not force and not ipautil.user_input("Continue to delete?", False):
@ -548,7 +539,7 @@ def del_master(realm, hostname, options):
thisrepl = replication.ReplicationManager(realm, options.host, thisrepl = replication.ReplicationManager(realm, options.host,
options.dirman_passwd) options.dirman_passwd)
except Exception, e: except Exception, e:
print "Failed to connect to server %s: %s" % (options.host, convert_error(e)) print "Failed to connect to server %s: %s" % (options.host, e)
sys.exit(1) sys.exit(1)
# 2. Ensure we have an agreement with the master # 2. Ensure we have an agreement with the master
@ -577,7 +568,7 @@ def del_master(realm, hostname, options):
try: try:
delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd) delrepl = replication.ReplicationManager(realm, hostname, options.dirman_passwd)
except Exception, e: except Exception, e:
print "Connection to '%s' failed: %s" % (hostname, convert_error(e)) print "Connection to '%s' failed: %s" % (hostname, e)
if not options.force: if not options.force:
print "Unable to delete replica '%s'" % hostname print "Unable to delete replica '%s'" % hostname
sys.exit(1) sys.exit(1)
@ -587,7 +578,8 @@ def del_master(realm, hostname, options):
if force_del: if force_del:
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), thisrepl.suffix) dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), thisrepl.suffix)
entries = thisrepl.conn.get_entries(dn, ldap.SCOPE_ONELEVEL) entries = thisrepl.conn.get_entries(
dn, thisrepl.conn.SCOPE_ONELEVEL)
replica_names = [] replica_names = []
for entry in entries: for entry in entries:
replica_names.append(entry.single_value('cn')) replica_names.append(entry.single_value('cn'))
@ -617,10 +609,12 @@ def del_master(realm, hostname, options):
if delrepl and not winsync: if delrepl and not winsync:
masters_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm)) masters_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
try: try:
masters = delrepl.conn.get_entries(masters_dn, ldap.SCOPE_ONELEVEL) masters = delrepl.conn.get_entries(
masters_dn, delrepl.conn.SCOPE_ONELEVEL)
except Exception, e: except Exception, e:
masters = [] masters = []
print "Failed to read masters data from '%s': %s" % (delrepl.hostname, convert_error(e)) print "Failed to read masters data from '%s': %s" % (
delrepl.hostname, e)
print "Skipping calculation to determine if one or more masters would be orphaned." print "Skipping calculation to determine if one or more masters would be orphaned."
if not options.force: if not options.force:
sys.exit(1) sys.exit(1)
@ -672,7 +666,8 @@ def del_master(realm, hostname, options):
if not del_link(realm, r, hostname, options.dirman_passwd, force=True): if not del_link(realm, r, hostname, options.dirman_passwd, force=True):
print "Unable to remove replication agreement for %s from %s." % (hostname, r) print "Unable to remove replication agreement for %s from %s." % (hostname, r)
except Exception, e: except Exception, e:
print "There were issues removing a connection for %s from %s: %s" % (hostname, r, convert_error(e)) print ("There were issues removing a connection for %s "
"from %s: %s" % (hostname, r, e))
# 5. Clean RUV for the deleted master # 5. Clean RUV for the deleted master
if repltype == replication.IPA_REPLICA: if repltype == replication.IPA_REPLICA:
@ -685,7 +680,7 @@ def del_master(realm, hostname, options):
try: try:
thisrepl.replica_cleanup(hostname, realm, force=True) thisrepl.replica_cleanup(hostname, realm, force=True)
except Exception, e: except Exception, e:
print "Failed to cleanup %s entries: %s" % (hostname, convert_error(e)) print "Failed to cleanup %s entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
# 7. And clean up the removed replica DNS entries if any. # 7. And clean up the removed replica DNS entries if any.
@ -701,7 +696,7 @@ def del_master(realm, hostname, options):
bind = bindinstance.BindInstance() bind = bindinstance.BindInstance()
bind.remove_master_dns_records(hostname, realm, realm.lower()) bind.remove_master_dns_records(hostname, realm, realm.lower())
except Exception, e: except Exception, e:
print "Failed to cleanup %s DNS entries: %s" % (hostname, convert_error(e)) print "Failed to cleanup %s DNS entries: %s" % (hostname, e)
print "You may need to manually remove them from the tree" print "You may need to manually remove them from the tree"
def add_link(realm, replica1, replica2, dirman_passwd, options): def add_link(realm, replica1, replica2, dirman_passwd, options):
@ -743,11 +738,11 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
# the directory server and kill the connection # the directory server and kill the connection
try: try:
repl1 = replication.ReplicationManager(realm, replica1, dirman_passwd) repl1 = replication.ReplicationManager(realm, replica1, dirman_passwd)
except (ldap.NO_SUCH_OBJECT, errors.NotFound): except errors.NotFound:
print "Cannot find replica '%s'" % replica1 print "Cannot find replica '%s'" % replica1
return return
except Exception, e: except Exception, e:
print "Failed to connect to '%s': %s" % (replica1, convert_error(e)) print "Failed to connect to '%s': %s" % (replica1, e)
return return
if options.winsync: if options.winsync:
@ -929,17 +924,6 @@ except SystemExit, e:
sys.exit(e) sys.exit(e)
except RuntimeError, e: except RuntimeError, e:
sys.exit(e) sys.exit(e)
except ldap.INVALID_CREDENTIALS:
print "Invalid password"
sys.exit(1)
except ldap.INSUFFICIENT_ACCESS:
print "Insufficient access"
sys.exit(1)
except ldap.LOCAL_ERROR, e:
print e.args[0]['info']
sys.exit(1)
except ldap.SERVER_DOWN, e:
print e.args[0]['desc']
except Exception, e: except Exception, e:
print "unexpected error: %s" % str(e) print "unexpected error: %s" % str(e)
sys.exit(1) sys.exit(1)

View File

@ -24,39 +24,31 @@ Upgrade configuration files to a newer template.
""" """
import sys import sys
try: import re
from ipapython import ipautil, sysrestore, version, services import os
from ipapython.config import IPAOptionParser import shutil
from ipapython.ipa_log_manager import * import pwd
from ipapython import certmonger import fileinput
from ipapython import dogtag
from ipapython.dn import DN from ipalib import api
from ipaserver.install import installutils import ipalib.util
from ipaserver.install import dsinstance import ipalib.errors
from ipaserver.install import httpinstance from ipapython import ipautil, sysrestore, version, services
from ipaserver.install import memcacheinstance from ipapython.config import IPAOptionParser
from ipaserver.install import bindinstance from ipapython.ipa_log_manager import *
from ipaserver.install import service from ipapython import certmonger
from ipaserver.install import cainstance from ipapython import dogtag
from ipaserver.install import certs from ipapython.dn import DN
from ipaserver.install import sysupgrade from ipaserver.install import installutils
import ldap from ipaserver.install import dsinstance
import re from ipaserver.install import httpinstance
import os from ipaserver.install import memcacheinstance
import shutil from ipaserver.install import bindinstance
import pwd from ipaserver.install import service
import fileinput from ipaserver.install import cainstance
from ipalib import api from ipaserver.install import certs
import ipalib.util from ipaserver.install import sysupgrade
import ipalib.errors
except ImportError:
print >> sys.stderr, """\
There was a problem importing one of the required Python modules. The
error was:
%s
""" % sys.exc_value
sys.exit(1)
def parse_options(): def parse_options():
parser = IPAOptionParser(version=version.VERSION) parser = IPAOptionParser(version=version.VERSION)
@ -741,7 +733,7 @@ def main():
ds = dsinstance.DsInstance() ds = dsinstance.DsInstance()
ds.start() ds.start()
memcache.create_instance('MEMCACHE', fqdn, None, ipautil.realm_to_suffix(api.env.realm)) memcache.create_instance('MEMCACHE', fqdn, None, ipautil.realm_to_suffix(api.env.realm))
except (ldap.ALREADY_EXISTS, ipalib.errors.DuplicateEntry): except ipalib.errors.DuplicateEntry:
pass pass
cleanup_kdc(fstore) cleanup_kdc(fstore)

View File

@ -37,8 +37,6 @@ from ipapython.dn import DN
from ipaserver.install import replication from ipaserver.install import replication
from ipaserver.install import dsinstance from ipaserver.install import dsinstance
import ldap
import pyasn1.codec.ber.decoder import pyasn1.codec.ber.decoder
import struct import struct
@ -260,7 +258,7 @@ class KrbInstance(service.Service):
try: try:
res = self.admin_conn.get_entries( res = self.admin_conn.get_entries(
DN(('cn', 'mapping'), ('cn', 'sasl'), ('cn', 'config')), DN(('cn', 'mapping'), ('cn', 'sasl'), ('cn', 'config')),
ldap.SCOPE_ONELEVEL, self.admin_conn.SCOPE_ONELEVEL,
"(objectclass=nsSaslMapping)") "(objectclass=nsSaslMapping)")
for r in res: for r in res:
try: try:
@ -360,8 +358,8 @@ class KrbInstance(service.Service):
def __write_stash_from_ds(self): def __write_stash_from_ds(self):
try: try:
entries = self.admin_conn.get_entries(self.get_realm_suffix(), entries = self.admin_conn.get_entries(
ldap.SCOPE_SUBTREE) self.get_realm_suffix(), self.admin_conn.SCOPE_SUBTREE)
# TODO: Ensure we got only one entry # TODO: Ensure we got only one entry
entry = entries[0] entry = entries[0]
except errors.NotFound, e: except errors.NotFound, e:

View File

@ -22,7 +22,6 @@ from ipaserver.install.plugins.baseupdate import PreUpdate, PostUpdate
from ipalib import api, errors from ipalib import api, errors
from ipapython import ipautil from ipapython import ipautil
from ipapython.dn import DN, EditableDN from ipapython.dn import DN, EditableDN
import ldap as _ldap
def entry_to_update(entry): def entry_to_update(entry):
""" """
@ -66,9 +65,9 @@ class GenerateUpdateMixin(object):
# If the old entries don't exist the server has already been updated. # If the old entries don't exist the server has already been updated.
try: try:
(definitions_managed_entries, truncated) = ldap.find_entries( definitions_managed_entries, truncated = ldap.find_entries(
searchfilter, ['*'], old_definition_container, _ldap.SCOPE_ONELEVEL, normalize=False searchfilter, ['*'], old_definition_container,
) ldap.SCOPE_ONELEVEL, normalize=False)
except errors.NotFound, e: except errors.NotFound, e:
return (False, update_list) return (False, update_list)

View File

@ -24,8 +24,6 @@ import pwd
import time import time
import datetime import datetime
import ldap
from ipapython import sysrestore from ipapython import sysrestore
from ipapython import ipautil from ipapython import ipautil
from ipapython import dogtag from ipapython import dogtag
@ -249,10 +247,12 @@ class Service(object):
self.ldap_disconnect() self.ldap_disconnect()
self.ldap_connect() self.ldap_connect()
dn = DN(('krbprincipalname', self.principal), ('cn', 'services'), ('cn', 'accounts'), self.suffix) dn = DN(('krbprincipalname', self.principal), ('cn', 'services'),
mod = [(ldap.MOD_ADD, 'userCertificate', self.dercert)] ('cn', 'accounts'), self.suffix)
entry = self.admin_conn.get_entry(dn)
entry.setdefault('userCertificate', []).append(self.dercert)
try: try:
self.admin_conn.modify_s(dn, mod) self.admin_conn.update_entry(entry)
except Exception, e: except Exception, e:
root_logger.critical("Could not add certificate to service %s entry: %s" % (self.principal, str(e))) root_logger.critical("Could not add certificate to service %s entry: %s" % (self.principal, str(e)))
@ -387,7 +387,7 @@ class Service(object):
try: try:
self.admin_conn.add_entry(entry) self.admin_conn.add_entry(entry)
except (ldap.ALREADY_EXISTS, errors.DuplicateEntry), e: except (errors.DuplicateEntry), e:
root_logger.debug("failed to add %s Service startup entry" % name) root_logger.debug("failed to add %s Service startup entry" % name)
raise e raise e

View File

@ -237,12 +237,10 @@ digits and nothing else follows.
''' '''
from lxml import etree from lxml import etree
import urllib
import urllib2 import urllib2
import datetime import datetime
import time import time
from ipapython.dn import DN from ipapython.dn import DN
from ldap.filter import escape_filter_chars
import ipapython.dogtag import ipapython.dogtag
from ipapython import ipautil from ipapython import ipautil
@ -1267,11 +1265,17 @@ class ra(rabase.rabase):
Check if a specified host is a master for a specified service. Check if a specified host is a master for a specified service.
""" """
base_dn = DN(('cn', host), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn) ldap2 = self.api.Backend.ldap2
filter = '(&(objectClass=ipaConfigObject)(cn=%s)(ipaConfigString=enabledService))' % escape_filter_chars(service) base_dn = DN(('cn', host), ('cn', 'masters'), ('cn', 'ipa'),
('cn', 'etc'), api.env.basedn)
filter_attrs = {
'objectClass': 'ipaConfigObject',
'cn': service,
'ipaConfigString': 'enabledService',
}
filter = ldap2.make_filter(filter_attrs, rules='&')
try: try:
ldap2 = self.api.Backend.ldap2 ent, trunc = ldap2.find_entries(filter=filter, base_dn=base_dn)
ent,trunc = ldap2.find_entries(filter=filter, base_dn=base_dn)
if len(ent): if len(ent):
return True return True
except Exception, e: except Exception, e:
@ -1286,11 +1290,17 @@ class ra(rabase.rabase):
Select any host which is a master for a specified service. Select any host which is a master for a specified service.
""" """
base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn) ldap2 = self.api.Backend.ldap2
filter = '(&(objectClass=ipaConfigObject)(cn=%s)(ipaConfigString=enabledService))' % escape_filter_chars(service) base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'),
api.env.basedn)
filter_attrs = {
'objectClass': 'ipaConfigObject',
'cn': service,
'ipaConfigString': 'enabledService',
}
filter = ldap2.make_filter(filter_attrs, rules='&')
try: try:
ldap2 = self.api.Backend.ldap2 ent, trunc = ldap2.find_entries(filter=filter, base_dn=base_dn)
ent,trunc = ldap2.find_entries(filter=filter, base_dn=base_dn)
if len(ent): if len(ent):
entry = random.choice(ent) entry = random.choice(ent)
dn = entry[0] dn = entry[0]