Replace entry.getValue by entry.single_value

Part of the work for: https://fedorahosted.org/freeipa/ticket/2660
This commit is contained in:
Petr Viktorin
2013-01-21 07:40:42 -05:00
committed by Martin Kosek
parent 66eaf1220d
commit f5c404c65d
11 changed files with 94 additions and 88 deletions

View File

@@ -217,9 +217,9 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
try:
cadn = DN(('cn', 'CA'), DN(ent.dn))
entry = conn.getEntry(cadn, ldap.SCOPE_BASE)
peers[ent.getValue('cn')] = ['master', '']
peers[ent.single_value('cn')] = ['master', '']
except errors.NotFound:
peers[ent.getValue('cn')] = ['CA not configured', '']
peers[ent.single_value('cn')] = ['CA not configured', '']
except Exception, e:
sys.exit("Failed to get data from '%s' while trying to list replicas: %s" % (host, convert_error(e)))
@@ -235,13 +235,19 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
entries = repl.find_replication_agreements()
for entry in entries:
print '%s' % entry.getValue('nsds5replicahost')
print '%s' % entry.single_value('nsds5replicahost', None)
if verbose:
print " last init status: %s" % entry.getValue('nsds5replicalastinitstatus')
print " last init ended: %s" % str(ipautil.parse_generalized_time(entry.getValue('nsds5replicalastinitend')))
print " last update status: %s" % entry.getValue('nsds5replicalastupdatestatus')
print " last update ended: %s" % str(ipautil.parse_generalized_time(entry.getValue('nsds5replicalastupdateend')))
print " last init status: %s" % entry.single_value(
'nsds5replicalastinitstatus', None)
print " last init ended: %s" % str(
ipautil.parse_generalized_time(
entry.single_value('nsds5replicalastinitend')))
print " last update status: %s" % entry.single_value(
'nsds5replicalastupdatestatus', None)
print " last update ended: %s" % str(
ipautil.parse_generalized_time(
entry.single_value('nsds5replicalastupdateend')))
def del_link(realm, replica1, replica2, dirman_passwd, force=False):
@@ -257,7 +263,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
# Find the DN of the replication agreement to remove
replica1_dn = None
for e in repl_list1:
if e.getValue('nsDS5ReplicaHost') == replica2:
if e.single_value('nsDS5ReplicaHost', None) == replica2:
replica1_dn = e.dn
break
@@ -293,7 +299,7 @@ def del_link(realm, replica1, replica2, dirman_passwd, force=False):
# Find the DN of the replication agreement to remove
replica2_dn = None
for e in repl_list:
if e.getValue('nsDS5ReplicaHost') == replica1:
if e.single_value('nsDS5ReplicaHost', None) == replica1:
replica2_dn = e.dn
break
@@ -401,7 +407,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
repl1 = get_cs_replication_manager(realm, replica1, dirman_passwd)
entries = repl1.find_replication_agreements()
for e in entries:
if e.getValue('nsDS5ReplicaHost') == replica2:
if e.single_value('nsDS5ReplicaHost', None) == replica2:
sys.exit('This replication agreement already exists.')
repl1.hostnames = [replica1, replica2]

View File

@@ -129,7 +129,7 @@ def main():
except Exception, 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)
managed_entries = [entry.getValue('cn') for entry in entries]
managed_entries = [entry.single_value('cn') for entry in entries]
if managed_entries:
print "Available Managed Entry Definitions:"
for managed_entry in managed_entries:
@@ -151,7 +151,7 @@ def main():
)
disable_attr = '(objectclass=disable)'
try:
org_filter = entry.getValue('originfilter')
org_filter = entry.single_value('originfilter', None)
disabled = re.search(r'%s' % disable_attr, org_filter)
except KeyError:
sys.exit("%s is not a valid Managed Entry" % def_dn)

View File

@@ -162,7 +162,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
return
else:
for ent in entries:
peers[ent.getValue('cn')] = ['master', '']
peers[ent.single_value('cn')] = ['master', '']
dn = DN(('cn', 'replicas'), ('cn', 'ipa'), ('cn', 'etc'), ipautil.realm_to_suffix(realm))
try:
@@ -171,7 +171,8 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
pass
else:
for ent in entries:
peers[ent.getValue('cn')] = ent.getValue('ipaConfigString').split(':')
config_string = ent.single_value('ipaConfigString')
peers[ent.single_value('cn')] = config_string.split(':')
if not replica:
for k, p in peers.iteritems():
@@ -207,13 +208,18 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
return
for entry in entries:
print '%s: %s' % (entry.getValue('nsds5replicahost'), ent_type)
print '%s: %s' % (entry.single_value('nsds5replicahost', None), ent_type)
if verbose:
print " last init status: %s" % entry.getValue('nsds5replicalastinitstatus')
print " last init ended: %s" % str(ipautil.parse_generalized_time(entry.getValue('nsds5replicalastinitend')))
print " last update status: %s" % entry.getValue('nsds5replicalastupdatestatus')
print " last update ended: %s" % str(ipautil.parse_generalized_time(entry.getValue('nsds5replicalastupdateend')))
print " last init status: %s" % entry.single_value(
'nsds5replicalastinitstatus', None)
print " last init ended: %s" % str(ipautil.parse_generalized_time(
entry.single_value('nsds5replicalastinitend')))
print " last update status: %s" % entry.single_value(
'nsds5replicalastupdatestatus', None)
print " last update ended: %s" % str(
ipautil.parse_generalized_time(
entry.single_value('nsds5replicalastupdateend')))
def del_link(realm, replica1, replica2, dirman_passwd, force=False):
"""
@@ -455,12 +461,12 @@ def list_clean_ruv(realm, host, dirman_passwd, verbose):
else:
print "CLEANALLRUV tasks"
for entry in entries:
name = entry.getValue('cn').replace('clean ', '')
status = entry.getValue('nsTaskStatus')
name = entry.single_value('cn').replace('clean ', '')
status = entry.single_value('nsTaskStatus', None)
print "RID %s: %s" % (name, status)
if verbose:
print str(dn)
print entry.getValue('nstasklog')
print entry.single_value('nstasklog', None)
print
@@ -472,12 +478,12 @@ def list_clean_ruv(realm, host, dirman_passwd, verbose):
else:
print "Abort CLEANALLRUV tasks"
for entry in entries:
name = entry.getValue('cn').replace('abort ', '')
status = entry.getValue('nsTaskStatus')
name = entry.single_value('cn').replace('abort ', '')
status = entry.single_value('nsTaskStatus', None)
print "RID %s: %s" % (name, status)
if verbose:
print str(dn)
print entry.getValue('nstasklog')
print entry.single_value('nstasklog', None)
def check_last_link(delrepl, realm, dirman_passwd, force):
"""
@@ -583,7 +589,7 @@ def del_master(realm, hostname, options):
entries = thisrepl.conn.getList(dn, ldap.SCOPE_ONELEVEL)
replica_names = []
for entry in entries:
replica_names.append(entry.getValue('cn'))
replica_names.append(entry.single_value('cn'))
# The host we're removing gets included in this list, remove it.
# Otherwise we try to delete an agreement from the host to itself.
try:
@@ -715,7 +721,7 @@ def add_link(realm, replica1, replica2, dirman_passwd, options):
if repl.get_agreement_type(replica2) == replication.WINSYNC:
agreement = repl.get_replication_agreement(replica2)
sys.exit("winsync agreement already exists on subtree %s" %
agreement.getValue('nsds7WindowsReplicaSubtree'))
agreement.single_value('nsds7WindowsReplicaSubtree', None))
else:
sys.exit("A replication agreement to %s already exists" % replica2)
except errors.NotFound:
@@ -808,7 +814,7 @@ def re_initialize(realm, thishost, fromhost, dirman_passwd):
# If the agreement doesn't have nsDS5ReplicatedAttributeListTotal it means
# we did not replicate memberOf, do so now.
if not agreement.getValue('nsDS5ReplicatedAttributeListTotal'):
if not agreement.single_value('nsDS5ReplicatedAttributeListTotal', None):
ds = dsinstance.DsInstance(realm_name = realm, dm_password = dirman_passwd)
ds.init_memberof()

View File

@@ -164,7 +164,7 @@ class ADTRUSTInstance(service.Service):
self.print_msg("Samba domain object not found")
return
dom_sid = dom_entry.getValue(self.ATTR_SID)
dom_sid = dom_entry.single_value(self.ATTR_SID, None)
if not dom_sid:
self.print_msg("Samba domain object does not have a SID")
return
@@ -182,7 +182,7 @@ class ADTRUSTInstance(service.Service):
self.print_msg("IPA admin group object not found")
return
if admin_entry.getValue(self.ATTR_SID):
if admin_entry.single_value(self.ATTR_SID, None):
self.print_msg("Admin SID already set, nothing to do")
else:
try:
@@ -192,7 +192,7 @@ class ADTRUSTInstance(service.Service):
except:
self.print_msg("Failed to modify IPA admin object")
if admin_group_entry.getValue(self.ATTR_SID):
if admin_group_entry.single_value(self.ATTR_SID, None):
self.print_msg("Admin group SID already set, nothing to do")
else:
try:
@@ -224,7 +224,7 @@ class ADTRUSTInstance(service.Service):
self.print_msg("Samba domain object not found")
return
if dom_entry.getValue(self.ATTR_FALLBACK_GROUP):
if dom_entry.single_value(self.ATTR_FALLBACK_GROUP, None):
self.print_msg("Fallback group already set, nothing to do")
return
@@ -269,12 +269,12 @@ class ADTRUSTInstance(service.Service):
"local domain.")
raise RuntimeError("Too many ID ranges\n")
if res[0].getValue('ipaBaseRID') or \
res[0].getValue('ipaSecondaryBaseRID'):
if res[0].single_value('ipaBaseRID', None) or \
res[0].single_value('ipaSecondaryBaseRID', None):
self.print_msg("RID bases already set, nothing to do")
return
size = res[0].getValue('ipaIDRangeSize')
size = res[0].single_value('ipaIDRangeSize', None)
if abs(self.rid_base - self.secondary_rid_base) > size:
self.print_msg("Primary and secondary RID base are too close. " \
"They have to differ at least by %d." % size)
@@ -719,7 +719,7 @@ class ADTRUSTInstance(service.Service):
raise ValueError("No local ID range and no admins group found.\n" \
"Add local ID range manually and try again!")
base_id = int(entry.getValue('gidNumber'))
base_id = int(entry.single_value('gidNumber'))
id_range_size = 200000
id_filter = "(&" \

View File

@@ -833,7 +833,7 @@ class DsInstance(service.Service):
dn = DN(('cn', 'default'), ('ou', 'profile'), self.suffix)
try:
entry = self.admin_conn.getEntry(dn, ldap.SCOPE_BASE, '(objectclass=*)')
srvlist = entry.getValue('defaultServerList', '')
srvlist = entry.single_value('defaultServerList', '')
srvlist = srvlist.split()
if not self.fqdn in srvlist:
srvlist.append(self.fqdn)

View File

@@ -127,11 +127,10 @@ class KrbInstance(service.Service):
managedby=[host_dn],
)
if 'krbpasswordexpiration' in service_entry.toDict():
host_entry['krbpasswordexpiration'] = [
service_entry.getValue('krbpasswordexpiration')]
host_entry['krbpasswordexpiration'] = service_entry[
'krbpasswordexpiration']
if 'krbticketflags' in service_entry.toDict():
host_entry['krbticketflags'] = [
service_entry.getValue('krbticketflags')]
host_entry['krbticketflags'] = service_entry['krbticketflags']
self.admin_conn.addEntry(host_entry)
def __common_setup(self, realm_name, host_name, domain_name, admin_password):
@@ -366,7 +365,8 @@ class KrbInstance(service.Service):
root_logger.critical("Could not find master key in DS")
raise e
krbMKey = pyasn1.codec.ber.decoder.decode(entry.getValue('krbmkey'))
krbMKey = pyasn1.codec.ber.decoder.decode(
entry.single_value('krbmkey', None))
keytype = int(krbMKey[0][1][0])
keydata = str(krbMKey[0][1][1])

View File

@@ -458,7 +458,7 @@ class LDAPUpdate:
self.error("Task lookup failure %s", e)
return
status = entry.getValue('nstaskstatus')
status = entry.single_value('nstaskstatus', None)
if status is None:
# task doesn't have a status yet
time.sleep(1)
@@ -816,7 +816,7 @@ class LDAPUpdate:
if entry.dn.endswith(DN(('cn', 'index'), ('cn', 'userRoot'),
('cn', 'ldbm database'), ('cn', 'plugins'),
('cn', 'config'))) and (added or updated):
taskid = self.create_index_task(entry.getValue('cn'))
taskid = self.create_index_task(entry.single_value('cn'))
self.monitor_index_task(taskid)
return

View File

@@ -47,7 +47,7 @@ class update_replica_attribute_lists(PreUpdate):
entries = repl.find_replication_agreements()
self.log.debug("Found %d agreement(s)", len(entries))
for replica in entries:
self.log.debug(replica.getValue('description'))
self.log.debug(replica.single_value('description', None))
self._update_attr(repl, replica,
'nsDS5ReplicatedAttributeList',
@@ -76,7 +76,7 @@ class update_replica_attribute_lists(PreUpdate):
:param values: List of values the attribute should hold
:param template: Template to use when adding attribute
"""
attrlist = replica.getValue(attribute)
attrlist = replica.single_value(attribute, None)
if attrlist is None:
self.log.debug("Adding %s", attribute)

View File

@@ -102,7 +102,7 @@ def enable_replication_version_checking(hostname, realm, dirman_passwd):
conn.do_sasl_gssapi_bind()
entry = conn.getEntry(DN(('cn', 'IPA Version Replication'), ('cn', 'plugins'), ('cn', 'config')),
ldap.SCOPE_BASE, 'objectclass=*')
if entry.getValue('nsslapd-pluginenabled') == 'off':
if entry.single_value('nsslapd-pluginenabled', None) == 'off':
conn.modify_s(entry.dn, [(ldap.MOD_REPLACE, 'nsslapd-pluginenabled', 'on')])
conn.unbind()
serverid = "-".join(realm.split("."))
@@ -124,8 +124,8 @@ def wait_for_task(conn, dn):
'nsTaskTotalItems']
while True:
entry = conn.get_entry(dn, attrlist)
if entry.getValue('nsTaskExitCode'):
exit_code = int(entry.getValue('nsTaskExitCode'))
if entry.single_value('nsTaskExitCode', None):
exit_code = int(entry.single_value('nsTaskExitCode'))
break
time.sleep(1)
return exit_code
@@ -183,8 +183,8 @@ class ReplicationManager(object):
except errors.NotFound:
pass
else:
if replica.getValue('nsDS5ReplicaId'):
return int(replica.getValue('nsDS5ReplicaId'))
if replica.single_value('nsDS5ReplicaId', None):
return int(replica.single_value('nsDS5ReplicaId'))
# Ok, either the entry doesn't exist or the attribute isn't set
# so get it from the other master
@@ -196,12 +196,12 @@ class ReplicationManager(object):
root_logger.debug("Unable to retrieve nsDS5ReplicaId from remote server")
raise
else:
if replica.getValue('nsDS5ReplicaId') is None:
if replica.single_value('nsDS5ReplicaId', None) is None:
root_logger.debug("Unable to retrieve nsDS5ReplicaId from remote server")
raise RuntimeError("Unable to retrieve nsDS5ReplicaId from remote server")
# Now update the value on the master
retval = int(replica.getValue('nsDS5ReplicaId'))
retval = int(replica.single_value('nsDS5ReplicaId'))
mod = [(ldap.MOD_REPLACE, 'nsDS5ReplicaId', str(retval + 1))]
try:
@@ -275,7 +275,7 @@ class ReplicationManager(object):
return res
for ent in ents:
res.append(ent.getValue('nsds5replicahost'))
res.append(ent.single_value('nsds5replicahost', None))
return res
@@ -382,7 +382,7 @@ class ReplicationManager(object):
('cn', 'config'), ('cn', 'ldbm database'),
('cn', 'plugins'), ('cn', 'config')),
['nsslapd-directory'])
dbdir = os.path.dirname(ent.getValue('nsslapd-directory'))
dbdir = os.path.dirname(ent.single_value('nsslapd-directory', None))
entry = conn.make_entry(
DN(('cn', 'changelog5'), ('cn', 'config')),
@@ -457,7 +457,7 @@ class ReplicationManager(object):
plgent = self.conn.getEntry(DN(('cn', 'Multimaster Replication Plugin'), ('cn', 'plugins'), ('cn', 'config')),
ldap.SCOPE_BASE, "(objectclass=*)", ['nsslapd-pluginPath'])
path = plgent.getValue('nsslapd-pluginPath')
path = plgent.single_value('nsslapd-pluginPath', None)
mod = [(ldap.MOD_REPLACE, 'nsslapd-state', 'backend'),
(ldap.MOD_ADD, 'nsslapd-backend', bename),
@@ -757,9 +757,10 @@ class ReplicationManager(object):
print "Error reading status from agreement", agmtdn
hasError = 1
else:
refresh = entry.getValue('nsds5BeginReplicaRefresh')
inprogress = entry.getValue('nsds5replicaUpdateInProgress')
status = entry.getValue('nsds5ReplicaLastInitStatus')
refresh = entry.single_value('nsds5BeginReplicaRefresh', None)
inprogress = entry.single_value('nsds5replicaUpdateInProgress',
None)
status = entry.single_value('nsds5ReplicaLastInitStatus', None)
if not refresh: # done - check status
if not status:
print "No status yet"
@@ -793,15 +794,16 @@ class ReplicationManager(object):
print "Error reading status from agreement", agmtdn
hasError = 1
else:
inprogress = entry.getValue('nsds5replicaUpdateInProgress')
status = entry.getValue('nsds5ReplicaLastUpdateStatus')
inprogress = entry.single_value('nsds5replicaUpdateInProgress',
None)
status = entry.single_value('nsds5ReplicaLastUpdateStatus', None)
try:
start = int(entry.getValue('nsds5ReplicaLastUpdateStart'))
except (ValueError, TypeError):
start = int(entry.single_value('nsds5ReplicaLastUpdateStart'))
except (ValueError, TypeError, KeyError):
start = 0
try:
end = int(entry.getValue('nsds5ReplicaLastUpdateEnd'))
except (ValueError, TypeError):
end = int(entry.single_value('nsds5ReplicaLastUpdateEnd'))
except (ValueError, TypeError, KeyError):
end = 0
# incremental update is done if inprogress is false and end >= start
done = inprogress and inprogress.lower() == 'false' and start <= end
@@ -1040,7 +1042,7 @@ class ReplicationManager(object):
root_logger.error("Using the first one only (%s)" % entries[0].dn)
dn = entries[0].dn
schedule = entries[0].getValue('nsds5replicaupdateschedule')
schedule = entries[0].single_value('nsds5replicaupdateschedule', None)
# On the remote chance of a match. We force a synch to happen right
# now by setting the schedule to something and quickly removing it.
@@ -1159,7 +1161,7 @@ class ReplicationManager(object):
try:
dn = DN(('cn', 'default'), ('ou', 'profile'), self.suffix)
ret = self.conn.getEntry(dn, ldap.SCOPE_BASE, '(objectclass=*)')
srvlist = ret.getValue('defaultServerList', '')
srvlist = ret.single_value('defaultServerList', '')
srvlist = srvlist[0].split()
if replica in srvlist:
srvlist.remove(replica)

View File

@@ -719,14 +719,6 @@ class LDAPEntry(dict):
yield self._dn
yield self
def getValue(self, name, default=None):
# FIXME: for backwards compatibility only
"""Get the first value for the attribute named name"""
value = self.data.get(name, default)
if isinstance(value, (list, tuple)):
return value[0]
return value
def toTupleList(self):
# FIXME: for backwards compatibility only
"""Convert the attrs and values to a list of 2-tuples. The first element

View File

@@ -110,7 +110,7 @@ class test_update(unittest.TestCase):
for item in ('top', 'nsContainer'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.getValue('cn'), 'test')
self.assertEqual(entry.single_value('cn'), 'test')
entries = self.ld.getList(self.user_dn, ldap.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
@@ -120,10 +120,10 @@ class test_update(unittest.TestCase):
for item in ('top', 'person', 'posixaccount', 'krbprincipalaux', 'inetuser'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.getValue('loginshell'), '/bin/bash')
self.assertEqual(entry.getValue('sn'), 'User')
self.assertEqual(entry.getValue('uid'), 'tuser')
self.assertEqual(entry.getValue('cn'), 'Test User')
self.assertEqual(entry.single_value('loginshell'), '/bin/bash')
self.assertEqual(entry.single_value('sn'), 'User')
self.assertEqual(entry.single_value('uid'), 'tuser')
self.assertEqual(entry.single_value('cn'), 'Test User')
def test_2_update(self):
@@ -136,7 +136,7 @@ class test_update(unittest.TestCase):
entries = self.ld.getList(self.user_dn, ldap.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.getValue('gecos'), 'Test User')
self.assertEqual(entry.single_value('gecos'), 'Test User')
def test_3_update(self):
"""
@@ -148,7 +148,7 @@ class test_update(unittest.TestCase):
entries = self.ld.getList(self.user_dn, ldap.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.getValue('gecos'), 'Test User New')
self.assertEqual(entry.single_value('gecos'), 'Test User New')
def test_4_update(self):
"""
@@ -160,7 +160,7 @@ class test_update(unittest.TestCase):
entries = self.ld.getList(self.user_dn, ldap.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
entry = entries[0]
self.assertEqual(entry.getValue('gecos'), 'Test User New2')
self.assertEqual(entry.single_value('gecos'), 'Test User New2')
def test_5_update(self):
"""
@@ -282,7 +282,7 @@ class test_update(unittest.TestCase):
for item in ('top', 'nsContainer'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.getValue('cn'), 'test')
self.assertEqual(entry.single_value('cn'), 'test')
entries = self.ld.getList(self.user_dn, ldap.SCOPE_BASE, 'objectclass=*', ['*'])
self.assertEqual(len(entries), 1)
@@ -292,10 +292,10 @@ class test_update(unittest.TestCase):
for item in ('top', 'person', 'posixaccount', 'krbprincipalaux', 'inetuser'):
self.assertTrue(item in objectclasses)
self.assertEqual(entry.getValue('loginshell'), '/bin/bash')
self.assertEqual(entry.getValue('sn'), 'User')
self.assertEqual(entry.getValue('uid'), 'tuser')
self.assertEqual(entry.getValue('cn'), 'Test User')
self.assertEqual(entry.single_value('loginshell'), '/bin/bash')
self.assertEqual(entry.single_value('sn'), 'User')
self.assertEqual(entry.single_value('uid'), 'tuser')
self.assertEqual(entry.single_value('cn'), 'Test User')
# Now delete