Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Authors: Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2008 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, either version 3 of the License, or # (at your option) any later version. # # 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, see <http://www.gnu.org/licenses/>. #
# Documentation can be found at http://freeipa.org/page/LdapUpdate
# TODO # save undo files?
return repr(self.value)
online=True, ldapi=False, plugins=False): ''' :parameters: dm_password Directory Manager password sub_dict substitution dictionary live_run Apply the changes or just test online Do an online LDAP update or use an experimental LDIF updater ldapi Bind using ldapi. This assumes autobind is enabled. plugins execute the pre/post update plugins
Data Structure Example: -----------------------
dn_by_rdn_count = { 3: 'cn=config,dc=example,dc=com': 4: 'cn=bob,ou=people,dc=example,dc=com', }
all_updates = { 'dn': 'cn=config,dc=example,dc=com': { 'dn': 'cn=config,dc=example,dc=com', 'default': ['attr1':default1'], 'updates': ['action:attr1:value1', 'action:attr2:value2] }, 'dn': 'cn=bob,ou=people,dc=example,dc=com': { 'dn': 'cn=bob,ou=people,dc=example,dc=com', 'default': ['attr3':default3'], 'updates': ['action:attr3:value3', 'action:attr4:value4], } }
The default and update lists are "dispositions"
'''
self.realm = sub_dict["REALM"] else: except krbV.Krb5Error: self.realm = None suffix = None
raise RuntimeError("Unable to determine hostname") fqdn = "ldapi://%%2fvar%%2frun%%2fslapd-%s.socket" % "-".join( self.realm.split(".") )
self.sub_dict["DOMAIN"] = domain
# Try out the connection/password elif os.getegid() == 0: try: # autobind conn.do_external_bind(self.pw_name) except errors.NotFound: # Fall back conn.do_sasl_gssapi_bind() else: conn.do_sasl_gssapi_bind() except (ldap.CONNECT_ERROR, ldap.SERVER_DOWN): raise RuntimeError("Unable to connect to LDAP server %s" % fqdn) except ldap.INVALID_CREDENTIALS: raise RuntimeError("The password provided is incorrect for LDAP server %s" % fqdn) except ldap.LOCAL_ERROR, e: raise RuntimeError('%s' % e.args[0].get('info', '').strip()) else: raise RuntimeError("Offline updates are not supported.")
# The following 2 functions were taken from the Python # documentation at http://docs.python.org/library/csv.html
# csv.py doesn't do Unicode; encode temporarily as UTF-8: dialect=dialect, delimiter=',', quotechar=quote_char, skipinitialspace=True, **kwargs) # decode UTF-8 back to Unicode, cell by cell:
"""On multi-arch systems some libraries may be in /lib64, /usr/lib64, etc. Determine if a suffix is needed based on the current architecture. """
else: return ""
except KeyError, e: raise BadSyntax("Unknown template keyword %s" % e)
"""Parse a comma-separated string into separate values and convert them into a list. This should handle quoted-strings with embedded commas """ quote_char = "'" else:
fd = sys.stdin else:
"""Tne Entry class is a bare LDAP entry. The Entity class has a lot more helper functions that we need, so convert to dict and then to Entity. """ entry[key] = ''
'Combine a new update with the list of total updates'
existing_update = all_updates[dn] if 'default' in update: disposition_list = existing_update.setdefault('default', []) disposition_list.extend(update['default']) elif 'updates' in update: disposition_list = existing_update.setdefault('updates', []) disposition_list.extend(update['updates']) else: self.debug("Unknown key in updates %s" % update.keys())
''' Add the new_update dict to the all_updates dict. If an entry in the new_update already has an entry in all_updates merge the two entries sensibly assuming the new entries take precedence. Otherwise just add the new entry. '''
for new_update in updates: for new_dn, new_entry in new_update.iteritems(): existing_entry = all_updates.get(new_dn) if existing_entry: # If the existing entry is marked for deletion but the # new entry is not also a delete then clear the delete # flag otherwise the newer update will be lost. if existing_entry.has_key('deleteentry') and not new_entry.has_key('deleteentry'): self.warning("ldapupdate: entry '%s' previously marked for deletion but" + " this subsequent update reestablishes it: %s", new_dn, new_entry) del existing_entry['deleteentry'] existing_entry.update(new_entry) else: all_updates[new_dn] = new_entry
"""Parse the update file into a dictonary of lists and apply the update for each DN in the file."""
''' Given a logical line containing an item to process perform the following:
* Strip leading & trailing whitespace * Substitute any variables * Get the action, attribute, and value * Each update has one list per disposition, append to specified disposition list '''
# Perform variable substitution on constructued line
raise BadSyntax, "Bad formatting on line %s:%d: %s" % (data_source_name, lcount, logical_line)
else:
new_value = attr + ":" + value disposition = "default" else:
''' When processing a dn is completed emit the update by merging it into the set of all updates. '''
# Iterate over source input lines
# strip trailing whitespace and newline
# skip comments and empty lines
# Starting new dn # Emit previous dn
else: # Process items belonging to dn raise BadSyntax, "dn is not defined in the update, data source=%s" % (data_source_name)
# If continuation line, append to existing logical line & continue, # otherwise flush the previous item. logical_line += source_line[1:] continue else:
"""Create a task to update an index for an attribute"""
# Sleep a bit to ensure previous operations are complete if self.live_run: time.sleep(5)
cn_uuid = uuid.uuid1() # cn_uuid.time is in nanoseconds, but other users of LDAPUpdate expect # seconds in 'TIME' so scale the value down self.sub_dict['TIME'] = int(cn_uuid.time/1e9) cn = "indextask_%s_%s_%s" % (attribute, cn_uuid.time, cn_uuid.clock_seq) dn = DN(('cn', cn), ('cn', 'index'), ('cn', 'tasks'), ('cn', 'config'))
e = ipaldap.Entry(dn)
e.setValues('objectClass', ['top', 'extensibleObject']) e.setValue('cn', cn) e.setValue('nsInstance', 'userRoot') e.setValues('nsIndexAttribute', attribute)
self.info("Creating task to index attribute: %s", attribute) self.debug("Task id: %s", dn)
if self.live_run: self.conn.addEntry(e)
return dn
"""Give a task DN monitor it and wait until it has completed (or failed) """
assert isinstance(dn, DN)
if not self.live_run: # If not doing this live there is nothing to monitor return
# Pause for a moment to give the task time to be created time.sleep(1)
attrlist = ['nstaskstatus', 'nstaskexitcode'] entry = None
while True: try: entry = self.conn.getEntry(dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist) except errors.NotFound, e: self.error("Task not found: %s", dn) return except errors.DatabaseError, e: self.error("Task lookup failure %s", e) return
status = entry.getValue('nstaskstatus') if status is None: # task doesn't have a status yet time.sleep(1) continue
if status.lower().find("finished") > -1: self.info("Indexing finished") break
self.debug("Indexing in progress") time.sleep(1)
return
"""Create the default entry from the values provided.
The return type is entity.Entity """
# This means that the entire entry needs to be created with add
for item in default: # We already do syntax-parsing so this is safe (attr, value) = item.split(':',1) e = entry.getValues(attr) if e: # multi-valued attribute e = list(e) e.append(value) else: e = value entry.setValues(attr, e)
return self._entry_to_entity(entry)
"""Retrieve an object from LDAP.
The return type is ipaldap.Entry """
""" updates is a list of changes to apply entry is the thing to apply them to
Returns the modified entry """ return entry
# We already do syntax-parsing so this is safe
# If the attribute is known to be a DN convert it to a DN object. # This has to be done after _parse_values() due to quoting and comma separated lists. update_values = [DN(x) for x in update_values]
else:
# Replacing objectClassess needs a special handling and # normalization of OC definitions to avoid update failures for # example when X-ORIGIN is the only difference if attr.lower() == "objectclasses": schema_elem_class = ObjectClass schema_elem_name = "ObjectClass" elif attr.lower() == "attributetypes": schema_elem_class = AttributeType schema_elem_name = "AttributeType"
if schema_elem_class is not None: schema_update = True oid_index = {} # build the OID index for replacing for schema_elem in entry_values: try: schema_elem_object = schema_elem_class(str(schema_elem)) except Exception, e: self.error('replace: cannot parse %s "%s": %s', schema_elem_name, schema_elem, e) continue # In a corner case, there may be more representations of # the same objectclass/attributetype due to the previous updates # We want to replace them all oid_index.setdefault(schema_elem_object.oid, []).append(schema_elem)
# Remove it, ignoring errors so we can blindly add it later self.debug("addifnew: '%s' to %s, current value %s", update_value, attr, entry_values) # Only add the attribute if it doesn't exist. Only works # with single-value attributes. if len(entry_values) == 0: entry_values.append(update_value) self.debug('addifnew: set %s to %s', attr, entry_values) entry.setValues(attr, entry_values) self.debug("addifexist: '%s' to %s, current value %s", update_value, attr, entry_values) # Only add the attribute if the entry doesn't exist. We # determine this based on whether it has an objectclass if entry.getValues('objectclass'): entry_values.append(update_value) self.debug('addifexist: set %s to %s', attr, entry_values) entry.setValues(attr, entry_values) entry_values.append(update_value) else: elif action == 'deleteentry': # skip this update type, it occurs in __delete_entries() return None elif action == 'replace': # value has the format "old::new" try: (old, new) = update_value.split('::', 1) except ValueError: raise BadSyntax, "bad syntax in replace, needs to be in the format old::new in %s" % update_value try: if schema_update: try: schema_elem_old = schema_elem_class(str(old)) except Exception, e: self.error('replace: cannot parse replaced %s "%s": %s', schema_elem_name, old, e) continue replaced_values = [] for schema_elem in oid_index.get(schema_elem_old.oid, []): schema_elem_object = schema_elem_class(str(schema_elem)) if str(schema_elem_old).lower() == str(schema_elem_object).lower(): # compare normalized values replaced_values.append(schema_elem) self.debug('replace: replace %s "%s" with "%s"', schema_elem_name, old, new) if not replaced_values: self.debug('replace: no match for replaced %s "%s"', schema_elem_name, old) continue for value in replaced_values: entry_values.remove(value) else: entry_values.remove(old) entry_values.append(new) self.debug('replace: updated value %s', entry_values) entry.setValues(attr, entry_values) except ValueError: self.debug('replace: %s not found, skipping', old)
"""The entity object currently lacks a str() method""" else:
"""Compare the schema in 's' with the current schema in the DS to see if anything has changed. This should account for syntax differences (like added parens that make no difference but are detected as a change by generateModList()).
This doesn't handle re-ordering of attributes. They are still detected as changes, so foo $ bar != bar $ foo.
return True if the schema has changed return False if it has not """ signature = inspect.getargspec(ldap.schema.SubSchema.__init__) if 'check_uniqueness' in signature.args: s = ldap.schema.SubSchema(s, check_uniqueness=0) else: s = ldap.schema.SubSchema(s) s = s.ldap_entry()
# Get a fresh copy and convert into a SubSchema n = self._get_entry(DN(('cn', 'schema')))[0]
# Convert IPA data types back to strings d = dict() for k,v in n.data.items(): d[k] = [str(x) for x in v]
# Convert to subschema dict n = ldap.schema.SubSchema(d) n = n.ldap_entry()
# Are they equal? if s == n: return False else: return True
# If the entry is going to be deleted no point in processing it.
update.get('default'))
# we should only ever get back one entry raise BadSyntax, "More than 1 entry returned on a dn search!? %s" % new_entry.dn # Doesn't exist, start with the default entry except errors.DatabaseError: # Doesn't exist, start with the default entry entry = new_entry self.info("New entry, using default value: %s", entry.dn)
# Bring this entry up to date # It might be None if it is just deleting an entry return
# New entries get their orig_data set to the entry itself. We want to # empty that so that everything appears new when generating the # modlist # entry.orig_data = {} # addifexist may result in an entry with only a # dn defined. In that case there is nothing to do. # It means the entry doesn't exist, so skip it. except errors.NotFound: # parent entry of the added entry does not exist # this may not be an error (e.g. entries in NIS container) self.info("Parent DN of %s may not exist, cannot create the entry", entry.dn) return except Exception, e: self.error("Add failure %s", e) else: # Update LDAP d = dict() e = entry.toDict() for k,v in e.items(): d[k] = [str(x) for x in v] updated = self.is_schema_updated(d) else: except errors.EmptyModlist: self.info("Entry already up-to-date") updated = False except errors.DatabaseError, e: self.error("Update failed: %s", e) updated = False except errors.ACIError, e: self.error("Update failed: %s", e) updated = False
('cn', 'ldbm database'), ('cn', 'plugins'), ('cn', 'config'))) and (added or updated): taskid = self.create_index_task(entry.getValue('cn')) self.monitor_index_task(taskid)
""" Run through all the updates again looking for any that should be deleted.
This must use a reversed list so that the longest entries are considered first so we don't end up trying to delete a parent and child in the wrong order. """
except errors.DatabaseError, e: self.error("Delete failed: %s", e)
"""Get all update files""" f = [] for path, subdirs, files in os.walk(root): for name in files: if fnmatch.fnmatch(name, "*.update"): f.append(os.path.join(path, name)) if not recursive: break f.sort() return f
self.conn = ipaldap.IPAdmin(ldapi=True, realm=self.realm) else: ldapi=False, realm=self.realm) elif os.getegid() == 0: try: # autobind self.conn.do_external_bind(self.pw_name) except errors.NotFound: # Fall back self.conn.do_sasl_gssapi_bind() else: self.conn.do_sasl_gssapi_bind() except ldap.LOCAL_ERROR, e: raise RuntimeError('%s' % e.args[0].get('info', '').strip()) else: raise RuntimeError("Offline updates are not supported.")
# For adds and updates we want to apply updates from shortest # to greatest length of the DN. For deletes we want the reverse.
"""Execute the update. files is a list of the update files to use.
returns True if anything was changed, otherwise False """
self.info('PRE_UPDATE') updates = api.Backend.updateclient.update(PRE_UPDATE, self.dm_password, self.ldapi, self.live_run) self.merge_updates(all_updates, updates)
except Exception, e: self.error("error reading update file '%s'", f) sys.exit(e)
finally:
self.info('POST_UPDATE') all_updates = {} updates = api.Backend.updateclient.update(POST_UPDATE, self.dm_password, self.ldapi, self.live_run) self.merge_updates(all_updates, updates) self._run_updates(all_updates)
""" Apply updates internally as opposed to from a file. updates is a dictionary containing the updates """
|