commit_id
string
repo
string
commit_message
string
diff
string
label
int64
e8f510e969284e0c0d62926c404540db66c21587
389ds/389-ds-base
Issue 50545 - Port remaining legacy tools to new python CLI Description: Created test that checks output syntax for dbmon to make sure it did not fail with error. Relates: https://pagure.io/389-ds-base/issue/50545 Reviewed by: firstyear, mreynolds (Thanks!)
commit e8f510e969284e0c0d62926c404540db66c21587 Author: Barbora Smejkalova <[email protected]> Date: Mon Jun 1 14:57:07 2020 +0200 Issue 50545 - Port remaining legacy tools to new python CLI Description: Created test that checks output syntax for dbmon to make sure it did not fail with error. Relates: https://pagure.io/389-ds-base/issue/50545 Reviewed by: firstyear, mreynolds (Thanks!) diff --git a/dirsrvtests/tests/suites/clu/dbmon_test.py b/dirsrvtests/tests/suites/clu/dbmon_test.py new file mode 100644 index 000000000..0c7a14b2a --- /dev/null +++ b/dirsrvtests/tests/suites/clu/dbmon_test.py @@ -0,0 +1,192 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2020 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import time +import subprocess +import pytest + +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_st +from lib389.cli_conf.monitor import db_monitor +from lib389.cli_base import FakeArgs + +pytestmark = pytest.mark.tier1 + +logging.getLogger(__name__).setLevel(logging.DEBUG) +log = logging.getLogger(__name__) + +OUTPUT_NO_INDEXES = [ + 'DB Monitor Report', + 'Database Cache:', + 'Cache Hit Ratio:', + 'Free Space:', + 'Free Percentage:', + 'RO Page Drops:', + 'Pages In:', + 'Pages Out:', + 'Normalized DN Cache:', + 'Cache Hit Ratio:', + 'Free Space:', + 'Free Percentage:', + 'DN Count:', + 'Evictions:', + 'Backends:', + 'dc=example,dc=com (userRoot):', + 'Entry Cache Hit Ratio:', + 'Entry Cache Count:', + 'Entry Cache Free Space:', + 'Entry Cache Free Percentage:', + 'Entry Cache Average Size:', + 'DN Cache Hit Ratio:', + 'DN Cache Count:', + 'DN Cache Free Space:', + 'DN Cache Free Percentage:', + 'DN Cache Average Size:' + ] + +OUTPUT_INDEXES = [ + 'DB Monitor Report', + 'Database Cache:', + 'Cache Hit Ratio:', + 'Free Space:', + 'Free Percentage:', + 'RO Page Drops:', + 'Pages In:', + 'Pages Out:', + 'Normalized DN Cache:', + 'Cache Hit Ratio:', + 'Free Space:', + 'Free Percentage:', + 'DN Count:', + 'Evictions:', + 'Backends:', + 'dc=example,dc=com (userRoot):', + 'Entry Cache Hit Ratio:', + 'Entry Cache Count:', + 'Entry Cache Free Space:', + 'Entry Cache Free Percentage:', + 'Entry Cache Average Size:', + 'DN Cache Hit Ratio:', + 'DN Cache Count:', + 'DN Cache Free Space:', + 'DN Cache Free Percentage:', + 'DN Cache Average Size:', + 'Indexes:', + 'Index: aci.db', + 'Cache Hit:', + 'Cache Miss:', + 'Page In:', + 'Page Out:', + 'Index: id2entry.db', + 'Index: objectclass.db', + 'Index: entryrdn.db' + ] + +JSON_OUTPUT = [ + 'date', + 'dbcache', + 'hit_ratio', + 'free', + 'free_percentage', + 'roevicts', + 'pagein', + 'pageout', + 'ndncache', + 'hit_ratio', + 'free', + 'free_percentage', + 'count', + 'evictions', + 'backends', + 'userRoot', + '"suffix": "dc=example,dc=com"', + 'entry_cache_count', + 'entry_cache_free', + 'entry_cache_free_percentage', + 'entry_cache_size', + 'entry_cache_hit_ratio', + 'dn_cache_count', + 'dn_cache_free', + 'dn_cache_free_percentage', + 'dn_cache_size', + 'dn_cache_hit_ratio', + 'indexes', + 'name', + 'objectclass.db', + 'cachehit', + 'cachemiss', + 'pagein', + 'pageout', + 'entryrdn.db', + 'aci.db', + 'id2entry.db' + ] + + +def clear_log(inst): + log.info('Clear the log') + inst.logcap.flush() + + [email protected] [email protected] [email protected](ds_is_older("1.4.2"), reason="Not implemented") +def test_dsconf_dbmon(topology_st): + """Test dbmon tool, that was ported from legacy tools to dsconf + + :id: 4d584ba9-12a9-4e90-ba9a-7e103affdac5 + :setup: Standalone instance + :steps: + 1. Create DS instance + 2. Run dbmon without --indexes + 3. Run dbmon with --indexes + 4. Run dbmon with --json + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + """ + + standalone = topology_st.standalone + + args = FakeArgs() + args.backends = DEFAULT_BENAME + args.indexes = False + args.json = False + + log.info('Sanity check for syntax') + db_monitor(standalone, DEFAULT_SUFFIX, topology_st.logcap.log, args) + for item in OUTPUT_NO_INDEXES: + assert topology_st.logcap.contains(item) + + clear_log(topology_st) + + log.info('Sanity check for --indexes output') + args.indexes = True + db_monitor(standalone, DEFAULT_SUFFIX, topology_st.logcap.log, args) + for index_item in OUTPUT_INDEXES: + assert topology_st.logcap.contains(index_item) + + clear_log(topology_st) + + log.info('Sanity check for --json output') + args.json = True + db_monitor(standalone, DEFAULT_SUFFIX, topology_st.logcap.log, args) + for json_item in JSON_OUTPUT: + assert topology_st.logcap.contains(json_item) + + clear_log(topology_st) + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE)
0
5a755180c192c79d65cc13e75ec6c473d7f11883
389ds/389-ds-base
Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV (#5676) * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV - Use readonly iteration on bdb should be txn less * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV - Added a comment Problem: Tests that: rebuilding the changelog RUV perform changelog trimming (i.e any test that are long enough) purge a Replica ID in the changelog (i.e demote a supplier/ cleanruv) Are hanging on lmdb until killed by the timeout because the changelog iterator loops on first entry. Reason: It is due to a difference in the way bdb and lmdb cusor get works when it is the first cursor operation and no key is provided. (bdb returns first key while lmdb fails). Because of that db-mdb layers use MDB_FIRST when no key is provided. Solution: Add a new dbimp function that iterates over a cursor calling a callback with key and value for all the records (until either the end of the database or the callback says to stop) This is more efficient than current code that walk the cursor through dbimpl API at the replication plugin level because it avoids the dbimpl API overhead (especially in lmdb case) furthermore it allows to easily handle the dbs specificity. Fixed the changelog RUVs rebuild to walk the changelog (using the new dbimpl function) only once instead of twice (collecting min and max for all replica ids then building both standard and purge ruv from these data Fixed the changelog trimming code to use the new changelog iterator, also fixed the way the purge ruv get updated (using now the first csn in the changelog (for the replicas whose csn get removed) instead of the last removed csn ) Fixed the changelog rid purge code to use the new changelog iterator Note: The changelog replication replay iterator is not impacted by this bug and is not changed. Also fixed a regression related to the addition of timeout in the test topology ( m1h1c1 topology is slightly different from the older version and is having a hub->supplier agreement which is making some test fail. Fixed that topology to remove that agreement.) Issue: [5661](#5661 Reviewed by: @tbordaz ( Thanks! )
commit 5a755180c192c79d65cc13e75ec6c473d7f11883 Author: progier389 <[email protected]> Date: Thu Mar 2 17:34:21 2023 +0100 Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV (#5676) * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV - Use readonly iteration on bdb should be txn less * Issue 5661 - LMDB hangs while Rebuilding the replication changelog RUV - Added a comment Problem: Tests that: rebuilding the changelog RUV perform changelog trimming (i.e any test that are long enough) purge a Replica ID in the changelog (i.e demote a supplier/ cleanruv) Are hanging on lmdb until killed by the timeout because the changelog iterator loops on first entry. Reason: It is due to a difference in the way bdb and lmdb cusor get works when it is the first cursor operation and no key is provided. (bdb returns first key while lmdb fails). Because of that db-mdb layers use MDB_FIRST when no key is provided. Solution: Add a new dbimp function that iterates over a cursor calling a callback with key and value for all the records (until either the end of the database or the callback says to stop) This is more efficient than current code that walk the cursor through dbimpl API at the replication plugin level because it avoids the dbimpl API overhead (especially in lmdb case) furthermore it allows to easily handle the dbs specificity. Fixed the changelog RUVs rebuild to walk the changelog (using the new dbimpl function) only once instead of twice (collecting min and max for all replica ids then building both standard and purge ruv from these data Fixed the changelog trimming code to use the new changelog iterator, also fixed the way the purge ruv get updated (using now the first csn in the changelog (for the replicas whose csn get removed) instead of the last removed csn ) Fixed the changelog rid purge code to use the new changelog iterator Note: The changelog replication replay iterator is not impacted by this bug and is not changed. Also fixed a regression related to the addition of timeout in the test topology ( m1h1c1 topology is slightly different from the older version and is having a hub->supplier agreement which is making some test fail. Fixed that topology to remove that agreement.) Issue: [5661](#5661 Reviewed by: @tbordaz ( Thanks! ) diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index 6502e2d19..2bb6f785f 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -26,6 +26,7 @@ #if defined(linux) #include <sys/vfs.h> #endif +#include "slap.h" #include "cl5.h" @@ -86,6 +87,12 @@ #define NO_DISK_SPACE 1024 #define MIN_DISK_SPACE 10485760 /* 10 MB */ +#define MAX_RETRIES 10 /* Maximum number of retry in case of db retryable error */ +#define CL5_TRIM_MAX_PER_TRANSACTION 100 +#define CL5_TRIM_MAX_LOOKUP_PER_TRANSACTION 10000 +#define CL5_PURGE_MAX_PER_TRANSACTION 1000 +#define CL5_PURGE_MAX_LOOKUP_PER_TRANSACTION 10000 + /***** Data Definitions *****/ /* possible changelog open modes */ @@ -112,7 +119,7 @@ struct cl5DBFileHandle /* info about the changelog file in the main database environment */ /* usage as CL5DBFile, but for new implementation use a new struct * can be replaced later - */ + */ { dbi_db_t *db; /* db handle to the changelog file */ dbi_env_t *dbEnv; /* db environment shared by all db files */ @@ -157,6 +164,44 @@ typedef struct cl5iterator typedef void (*VFP)(void *); +/* + * structures used to store transiently some data when working + * on RUV. They are faster than the standard RUV access because + * there is no lock involved and rids are sorted and + * it requires a single malloc block. + */ +typedef struct { + ReplicaId rid; + char new; + CSN mincsn; + CSN maxcsn; +} RID_INFO; + +typedef struct { + int nb; /* numbers of event in current txn */ + int nbmax; /* maximum number of event before closing txn */ + long tot; /* total numbers of event */ +} DBLCI_EVENT_COUNT; + +/* context for dblayer cursor iterator callbacks */ +typedef struct { + struct cl5DBFileHandle *cldb; + PRFileDesc *exportFile; /* Specific to _cl5ExportFile */ + dbi_cursor_t cursor; + CSN startcsn; + CSN csn; + long numToTrim; /* Specific to _cl5TrimReplica */ + Replica *r; /* Specific to _cl5TrimReplica */ + RUV *ruv; /* Specific to _cl5TrimReplica */ + RID_INFO *rids; /* csn per rid list */ + int nb_rids; /* csn per rid list size */ + int max_rids; /* csn per rid list max size */ + DBLCI_EVENT_COUNT changed; /* records changed */ + DBLCI_EVENT_COUNT seen; /* records seen */ + PRBool finished; /* Tells whether iteration should stop */ + ReplicaId rid2purge; /* Specific to _cl5PurgeRid */ +} DBLCI_CTX; + /***** Forward Declarations *****/ /* changelog initialization and cleanup */ @@ -173,9 +218,6 @@ static int _cl5ExportFile(PRFileDesc *prFile, cldb_Handle *cldb); static int _cl5Entry2DBData(const CL5Entry *entry, char **data, PRUint32 *len, void *clcrypt_handle); static int _cl5WriteOperation(cldb_Handle *cldb, const slapi_operation_parameters *op); static int _cl5WriteOperationTxn(cldb_Handle *cldb, const slapi_operation_parameters *op, void *txn); -static int _cl5GetFirstEntry(cldb_Handle *cldb, CL5Entry *entry, void **iterator, dbi_txn_t *txnid); -static int _cl5GetNextEntry(CL5Entry *entry, void *iterator); -static int _cl5CurrentDeleteEntry(void *iterator); static const char *_cl5OperationType2Str(int type); static int _cl5Str2OperationType(const char *str); static void _cl5WriteString(const char *str, char **buff); @@ -203,14 +245,12 @@ static int _cl5CheckMissingCSN(const CSN *minCsn, const RUV *supplierRUV, cldb_H /* changelog trimming */ static int cldb_IsTrimmingEnabled(cldb_Handle *cldb); static int _cl5TrimMain(void *param); -static void _cl5TrimReplica(Replica *r); -static void _cl5PurgeRID(cldb_Handle *cldb, ReplicaId cleaned_rid); -static int _cl5PurgeGetFirstEntry(cldb_Handle *cldb, CL5Entry *entry, void **iterator, dbi_txn_t *txnid, int rid, dbi_val_t *key); -static int _cl5PurgeGetNextEntry(CL5Entry *entry, void *iterator, dbi_val_t *key); +void _cl5TrimReplica(Replica *r); +void _cl5PurgeRID(cldb_Handle *cldb, ReplicaId cleaned_rid); static PRBool _cl5CanTrim(time_t time, long *numToTrim, Replica *replica, CL5Config *dbTrim); -static int _cl5ReadRUV(cldb_Handle *cldb, PRBool purge); +int _cl5ConstructRUVs (cldb_Handle *cldb); +int _cl5ReadRUVs(cldb_Handle *cldb); static int _cl5WriteRUV(cldb_Handle *cldb, PRBool purge); -static int _cl5ConstructRUV(cldb_Handle *cldb, PRBool purge); static int _cl5UpdateRUV (cldb_Handle *cldb, CSN *csn, PRBool newReplica, PRBool purge); static int _cl5GetRUV2Purge2(Replica *r, RUV **ruv); void trigger_cl_purging_thread(void *rid); @@ -311,7 +351,7 @@ _cldb_DeleteDB(Replica *replica) slapi_counter_increment(cldb->clThreads); be = slapi_be_select(replica_get_root(replica)); - + slapi_back_ctrl_info(be, BACK_INFO_DBENV_CLDB_REMOVE, (void *)(cldb->db)); cldb->db = NULL; @@ -542,9 +582,7 @@ cl5ImportLDIF(const char *clDir, const char *ldifFile, Replica *replica) } ruv_destroy(&cldb->maxRUV); ruv_destroy(&cldb->purgeRUV); - _cl5ReadRUV(cldb, PR_TRUE); - _cl5ReadRUV(cldb, PR_FALSE); - _cl5GetEntryCount(cldb); + _cl5ReadRUVs(cldb); pthread_mutex_unlock(&(cldb->stLock)); object_release(ruv_obj); @@ -938,7 +976,7 @@ cl5CreateReplayIteratorEx(Private_Repl_Protocol *prp, const RUV *consumerRuv, CL pthread_mutex_unlock(&(cldb->stLock)); /* iterate through the ruv in csn order to find first supplier for which - we can replay changes */ + we can replay changes */ rc = _cl5PositionCursorForReplay (consumerRID, consumerRuv, replica, iterator, NULL); if (rc != CL5_SUCCESS) { @@ -1142,12 +1180,6 @@ cl5GetOperationCount(Replica *replica) int count = 0; cldb_Handle *cldb = replica_get_cl_info(replica); - if (cldb->dbState == CL5_STATE_CLOSED) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "cl5GetOperationCount - Changelog is not initialized\n"); - return -1; - } - if (replica == NULL) /* compute total entry count */ { /* TBD (LK) get count for all backends @@ -1160,6 +1192,10 @@ cl5GetOperationCount(Replica *replica) } */ count = 0; + } else if (cldb->dbState == CL5_STATE_CLOSED) { + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, + "cl5GetOperationCount - Changelog is not initialized\n"); + return -1; } else /* return count for particular db */ { slapi_counter_increment(cldb->clThreads); @@ -1179,7 +1215,7 @@ cldb_UnSetReplicaDB(Replica *replica, void *arg) int rc = 0; cldb_Handle *cldb = replica_get_cl_info(replica); Slapi_Backend *be = slapi_be_select(replica_get_root(replica)); - + if (cldb == NULL) { slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "cldb_UnSetReplicaDB: cldb is NULL (okay if this is a consumer)\n"); @@ -1251,7 +1287,7 @@ cldb_SetReplicaDB(Replica *replica, void *arg) Slapi_Backend *be = slapi_be_select(replica_get_root(replica)); Object *ruv_obj = replica_get_ruv(replica); - + rc = slapi_back_get_info(be, BACK_INFO_DBENV_CLDB, (void **)&pDB); if (rc == 0) { cldb = (cldb_Handle *)slapi_ch_calloc(1, sizeof(cldb_Handle)); @@ -1265,9 +1301,7 @@ cldb_SetReplicaDB(Replica *replica, void *arg) /* coverity[leaked_storage] */ return CL5_SYSTEM_ERROR; } - _cl5ReadRUV(cldb, PR_TRUE); - _cl5ReadRUV(cldb, PR_FALSE); - _cl5GetEntryCount(cldb); + _cl5ReadRUVs(cldb); } object_release(ruv_obj); @@ -1334,7 +1368,7 @@ cldb_SetReplicaDB(Replica *replica, void *arg) slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "cldb_SetReplicaDB: cldb is set\n"); - + return rc; } @@ -1705,6 +1739,226 @@ cl5DBData2Entry(const char *data, PRUint32 len __attribute__((unused)), CL5Entry return rc; } +/* Get entry time from changelog record data without decoding the whole operation */ +int +cl5DBData2EntryTime(const char *data, time_t *entrytime) +{ + PRUint8 version; + char *pos = (char *)data; + PRUint32 thetime; + + PR_ASSERT(data && entrytime); + + /* ONREPL - check that we do not go beyond the end of the buffer */ + + /* read byte of version */ + version = (PRUint8)(*pos); + if (version != V_5 && version != V_6) { + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, + "cl5DBData2EntryTime - Invalid data version: %d\n", version); + return CL5_BAD_FORMAT; + } + pos += sizeof(version); + + if (version == V_6) { + /* In version 6 we set a flag to note if the changes are encrypted */ + pos += sizeof(PRUint8); + } + + /* read change type */ + pos++; + + /* need to do the copy first, to skirt around alignment problems on + certain architectures */ + memcpy((char *)&thetime, pos, sizeof(thetime)); + *entrytime = (time_t)PR_ntohl(thetime); + return CL5_SUCCESS; +} + +/* Map the dbi layer error code to the CL5_ ones */ +static int +_cl5Dberror(cldb_Handle *cldb, int rc, const char *errmsg) +{ + int clrc = CL5_SUCCESS; + int loglvl = SLAPI_LOG_ERR; + switch (rc) { + case DBI_RC_RETRY: + clrc = CL5_DB_RETRY; + loglvl = SLAPI_LOG_REPL; + break; + case DBI_RC_NOTFOUND: + clrc = CL5_NOTFOUND; + break; + case DBI_RC_SUCCESS: + clrc = CL5_SUCCESS; + errmsg = NULL; + break; + default: + if (rc>0 && rc<CL5_LAST_ERROR_CODE) { + /* Lets assume that: + * it is a CL5_ error already logged by the callback + */ + errmsg = NULL; + clrc = rc; + } else { + clrc = CL5_DB_ERROR; + } + break; + } + if (errmsg) { + slapi_log_err(loglvl, repl_plugin_name_cl, + "%s on changelog %s; db error - %d %s\n", + errmsg, cldb->ident, rc, dblayer_strerror(rc)); + } + return clrc; +} + +/* Iterate over a changelog cursor */ +int +_cl5Iterate(cldb_Handle *cldb, dbi_iterate_cb_t *action_cb, DBLCI_CTX *dblcictx, PRBool readonly) +{ + dbi_txn_t *txnid = NULL; + int rc = CL5_DB_RETRY; + int nbtries = 0; + CSN *startcsn = NULL; + + dblcictx->finished = PR_FALSE; + dblcictx->cldb = cldb; + while ( !slapi_is_shutting_down() && + ((rc == CL5_SUCCESS && dblcictx->finished == PR_FALSE) || + (rc == CL5_DB_RETRY && nbtries < MAX_RETRIES))) { + nbtries++; + dblcictx->changed.nb = 0; + dblcictx->seen.nb = 0; + if (rc == CL5_SUCCESS) { + /* action_cb have decided to abort/commit the txn + * then go on with the iteration + */ + startcsn = &dblcictx->csn; + } + if (startcsn) { + /* Save startcsn to be able to retry at the same place */ + dblcictx->startcsn = *startcsn; + startcsn = &dblcictx->startcsn; + } + if (!readonly || dblayer_is_lmdb(cldb->be)) { + /* + * if write operation are performed or if lmdb is used, a transaction is needed. + * In bdb case DB txn lock accessed pages until the end of the transaction. + * in lmdb case the read or write lock is global and also held until the end + * of the transaction. + */ + rc = TXN_BEGIN(cldb, NULL, &txnid, readonly); + if (rc != 0) { + rc = _cl5Dberror(cldb, rc, "_cl5Iterate - Failed to begin transaction"); + continue; + } + } else { + /* read-only opertion on bdb are transactionless, so no reason to abort txn + * after having seen some number of records + */ + dblcictx->seen.nbmax = 0; + } + /* create cursor */ + rc = dblayer_new_cursor(cldb->be, cldb->db, txnid, &dblcictx->cursor); + if (rc != 0) { + rc = _cl5Dberror(cldb, rc, "_cl5Iterate - Failed to create cursor"); + TXN_ABORT(cldb, txnid); + continue; + } + if (startcsn) { + char csnstr[CSN_STRSIZE] = ""; + dbi_val_t startingkey = {0}; + csn_as_string(startcsn, 0, csnstr); + dblayer_value_set(cldb->be, &startingkey, csnstr, CSN_STRSIZE); + rc = dblayer_cursor_iterate(&dblcictx->cursor, action_cb, &startingkey, dblcictx); + } else { + rc = dblayer_cursor_iterate(&dblcictx->cursor, action_cb, NULL, dblcictx); + } + if (dblcictx->seen.nbmax > 10 && rc == CL5_DB_LOCK_ERROR) { + /* + * Ran out of locks, need to restart the transaction. + * Reduce the the batch count and reset the key to + * the starting point. + * PR: Not sure weither this code is still working because dbimpl API layer + * may remap bdb error 12 to something else. + */ + dblcictx->seen.nbmax -= 10; + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, + "_cl5Iterate - Ran out of db locks while iterating on entries; " + "Reducing the batch value to %d and retry.\n", dblcictx->seen.nbmax); + nbtries = 0; + continue; + } + rc = _cl5Dberror(cldb, rc, NULL); + if (rc != CL5_NOTFOUND && rc != CL5_SUCCESS) { + dblcictx->changed.nb = 0; /* Tells to abort the txn */ + dblcictx->seen.nb = 0; + } + dblayer_cursor_op(&dblcictx->cursor, DBI_OP_CLOSE, NULL, NULL); + dblcictx->changed.tot += dblcictx->changed.nb; + dblcictx->seen.tot += dblcictx->seen.nb; + + if (txnid) { + if (dblcictx->changed.nb) { + int rc2 = TXN_COMMIT(cldb, txnid); + if (rc2 != DBI_RC_SUCCESS) { + rc = _cl5Dberror(cldb, rc2, "_cl5Iterate - Failed to commit transaction"); + } + } else { + int rc2 = TXN_ABORT(cldb, txnid); + if (rc2 != DBI_RC_SUCCESS) { + if (rc == CL5_SUCCESS || rc == CL5_NOTFOUND) { + rc = _cl5Dberror(cldb, rc2, "_cl5Iterate - Failed to abort transaction"); + } + } + } + } + } + if (rc == CL5_DB_RETRY && nbtries > MAX_RETRIES) { + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, + "_cl5Iterate - Too many db retries errors on changelog %s\n", + cldb->ident); + rc = CL5_DB_ERROR; + } + return rc; +} + +/* _cl5ConstructRUVs helper: Find or allocate sorted RID_INFO slot in DBLCI_CTX */ +RID_INFO * +_cl5GetRidInfo(DBLCI_CTX *dblcictx, ReplicaId rid, PRBool addifmissing) +{ + int idx = 0; + int idx_min = 0; + int idx_max = dblcictx->nb_rids-1; + while (idx_min <= idx_max) { + idx = (idx_min + idx_max) / 2; + if (dblcictx->rids[idx].rid == rid) { + return &dblcictx->rids[idx]; + } + if (dblcictx->rids[idx].rid > rid) { + idx_max = idx-1; + } else { + idx_min = idx+1; + } + } + /* Not found: lets allocates a new RID_INFO */ + if (addifmissing == PR_FALSE) { + return NULL; + } + dblcictx->nb_rids++; + if (dblcictx->nb_rids >= dblcictx->max_rids) { + dblcictx->max_rids += 200; + dblcictx->rids = (RID_INFO *)slapi_ch_realloc((void*)dblcictx->rids, dblcictx->max_rids * sizeof (RID_INFO)); + } + for (int i = dblcictx->nb_rids-2; i >= idx_min; i--) { + dblcictx->rids[i+1] = dblcictx->rids[i]; + } + dblcictx->rids[idx_min].new = 1; + dblcictx->rids[idx_min].rid = rid; + return &dblcictx->rids[idx_min]; +} + /* thread management functions */ static int _cl5DispatchTrimThread(Replica *replica) @@ -2291,142 +2545,88 @@ _cl5DoPurging(cleanruv_purge_data *purge_data) return; } +static inline int +_cl5CIEventCheckTxnEnd(DBLCI_EVENT_COUNT *ev) +{ + return (ev->nbmax && ev->nb >= ev->nbmax); +} + /* - * If the rid is not set it is the very first iteration of the changelog. - * If the rid is set, we are doing another pass, and we have a key as our - * starting point. + * _cl5Iterate callbacks helper + * Changelog cursor iterator callback common code initializer. + * Shoukd start all the _cl5CursorIterate callbacks. */ static int -_cl5PurgeGetFirstEntry(cldb_Handle *cldb, CL5Entry *entry, void **iterator, dbi_txn_t *txnid, int rid, dbi_val_t *key) +_cl5CICbInit(dbi_val_t *key, dbi_val_t *data, DBLCI_CTX *dblcictx) { - dbi_cursor_t cursor = {0}; - dbi_val_t data = {0}; - CL5Iterator *it; - int rc; - - /* create cursor */ - rc = dblayer_new_cursor(cldb->be, cldb->db, txnid, &cursor); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeGetFirstEntry - Failed to create cursor; db error - %d %s\n", rc, dblayer_strerror(rc)); - return CL5_DB_ERROR; - } - - if (!rid) { - dblayer_value_init(cldb->be, key); - } - dblayer_value_init(cldb->be, &data); - - while ((rc = dblayer_cursor_op(&cursor, - rid ? DBI_OP_MOVE_TO_KEY : DBI_OP_NEXT, key, &data)) == 0) { - /* skip service entries on the first pass (rid == 0)*/ - if (!rid && cl5HelperEntry((char *)key->data, NULL)) { - dblayer_value_free(cldb->be, &data); - dblayer_value_free(cldb->be, key); - continue; - } - - /* format entry */ - rc = cl5DBData2Entry(data.data, data.size, entry, cldb->clcrypt_handle); - dblayer_value_free(cldb->be, &data); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5PurgeGetFirstEntry - Failed to format entry: %d\n", rc); - goto done; - } - - it = (CL5Iterator *)slapi_ch_malloc(sizeof(CL5Iterator)); - it->cursor = cursor; - /* TBD do we need to lock the file in the iterator ?? */ - /* object_acquire (obj); */ - it->it_cldb = cldb; - *(CL5Iterator **)iterator = it; - - return CL5_SUCCESS; + /* Verify that we have a valid csn */ + if (key->size != CSN_STRSIZE) { + return DBI_RC_SUCCESS; + } + /* Update last csn */ + csn_init_by_string(&dblcictx->csn, data->data); + if (_cl5CIEventCheckTxnEnd(&dblcictx->seen) || + _cl5CIEventCheckTxnEnd(&dblcictx->changed)) { + /* + * returns DBI_RC_NOTFOUND so dblayer_cursor_iterate + * stops with DBI_RC_SUCCESS return code, then + * _cl5Iterate commits the txn and restart a new txn + * and iterate again starting from last seen record + * (i.e same key and data that the one we are + * currently processing ) + */ + return DBI_RC_NOTFOUND; } + dblcictx->seen.nb++; + return DBI_RC_SUCCESS; +} - dblayer_value_free(cldb->be, &data); - dblayer_value_free(cldb->be, key); - - /* walked of the end of the file */ - if (rc == DBI_RC_NOTFOUND) { - rc = CL5_NOTFOUND; - goto done; +/* + * _cl5Iterate callbacks helper + * Remove current entry from changelog. + */ +int +_cl5CICbRemoveEntry(DBLCI_CTX *dblcictx, const char *funcname) +{ + int rc = dblayer_cursor_op(&dblcictx->cursor,DBI_OP_DEL, NULL, NULL); + if (rc == DBI_RC_SUCCESS) { + /* decrement entry count */ + PR_AtomicDecrement(&dblcictx->cldb->entryCount); + dblcictx->changed.nb++; + } else { + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, + "%s - Failed to remove entry, err=%d %s\n", + funcname, rc, dblayer_strerror(rc)); } - - /* db error occured while iterating */ - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeGetFirstEntry - Failed to get entry; db error - %d %s\n", - rc, dblayer_strerror(rc)); - rc = CL5_DB_ERROR; - -done: - /* - * We didn't success in assigning this cursor to the iterator, - * so we need to free the cursor here. - */ - dblayer_cursor_op(&cursor, DBI_OP_CLOSE, NULL, NULL); - return rc; } /* - * Get the next entry. If we get a lock error we will restart the process - * starting at the current key. + * _cl5PurgeRid helper: dblayer_cursor_iterate callback. + * Returns: + * DBI_RC_SUCCESS to iterate on next entry + * DBI_RC_NOTFOUND to stop iteration with DBI_RC_SUCCESS code + * other DBI_RC_ code to stop iteration with that error code. */ -static int -_cl5PurgeGetNextEntry(CL5Entry *entry, void *iterator, dbi_val_t *key) +int +_cl5PurgeRidOnEntry(dbi_val_t *key, dbi_val_t *data, void *ctx) { - CL5Iterator *it; - dbi_val_t data = {0}; - int rc; - - it = (CL5Iterator *)iterator; - - dblayer_value_init(it->it_cldb->be, &data); - while ((rc = dblayer_cursor_op(&it->cursor, DBI_OP_NEXT, key, &data)) == 0) { - if (cl5HelperEntry((char *)key->data, NULL)) { - continue; - } - - /* format entry */ - rc = cl5DBData2Entry(data.data, data.size, entry, it->it_cldb->clcrypt_handle); - dblayer_value_free(it->it_cldb->be, &data); - if (rc != 0) { - if (rc != CL5_DB_LOCK_ERROR) { - /* Not a lock error, free the key */ - dblayer_value_free(it->it_cldb->be, key); - } - slapi_log_err(rc == CL5_DB_LOCK_ERROR ? SLAPI_LOG_REPL : SLAPI_LOG_ERR, - repl_plugin_name_cl, - "_cl5PurgeGetNextEntry - Failed to format entry: %d\n", - rc); - } + DBLCI_CTX *dblcictx = ctx; + ReplicaId rid = 0; + int rc = 0; + rc = _cl5CICbInit(key, data, dblcictx); + if (rc != DBI_RC_SUCCESS) { return rc; } - dblayer_value_free(it->it_cldb->be, &data); - /* walked of the end of the file or entry is out of range */ - if (rc == 0 || rc == DBI_RC_NOTFOUND) { - dblayer_value_free(it->it_cldb->be, key); - return CL5_NOTFOUND; + rid = csn_get_replicaid(&dblcictx->csn); + if (rid == dblcictx->rid2purge) { + rc = _cl5CICbRemoveEntry(dblcictx, __FUNCTION__); } - if (rc != CL5_DB_LOCK_ERROR) { - /* Not a lock error, free the key */ - dblayer_value_free(it->it_cldb->be, key); - } - - /* cursor operation failed */ - slapi_log_err(rc == CL5_DB_LOCK_ERROR ? SLAPI_LOG_REPL : SLAPI_LOG_ERR, - repl_plugin_name_cl, - "_cl5PurgeGetNextEntry - Failed to get entry; db error - %d %s\n", - rc, dblayer_strerror(rc)); - return rc; } -#define MAX_RETRIES 10 /* * _cl5PurgeRID(Object *obj, ReplicaId cleaned_rid) * @@ -2436,335 +2636,165 @@ _cl5PurgeGetNextEntry(CL5Entry *entry, void *iterator, dbi_val_t *key) * We save the key from the last iteration so we don't have to start from the * beginning for each new iteration. */ -static void +void _cl5PurgeRID(cldb_Handle *cldb, ReplicaId cleaned_rid) { - slapi_operation_parameters op = {0}; - ReplicaId csn_rid; - CL5Entry entry; - dbi_txn_t *txnid = NULL; - dbi_val_t key = {0}; - void *iterator = NULL; - long totalTrimmed = 0; - long trimmed = 0; - char *starting_key = NULL; - int batch_count = 0; - int db_lock_retry_count = 0; - int first_pass = 1; - int finished = 0; - int rc = 0; - - entry.op = &op; - - /* - * Keep processing the changelog until we are done, shutting down, or we - * maxed out on the db lock retries. - */ - while (!finished && db_lock_retry_count < MAX_RETRIES && !slapi_is_shutting_down()) { - trimmed = 0; - - /* - * Sleep a bit to allow others to use the changelog - we can't hog the - * changelog for the entire purge. - */ - DS_Sleep(PR_MillisecondsToInterval(100)); + DBLCI_CTX dblcictx = {0}; - rc = TXN_BEGIN(cldb, NULL, &txnid, 0); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Failed to begin transaction; db error - %d %s. " - "Changelog was not purged of rid(%d)\n", - rc, dblayer_strerror(rc), cleaned_rid); - return; - } + dblcictx.seen.nbmax = CL5_PURGE_MAX_LOOKUP_PER_TRANSACTION; + dblcictx.changed.nbmax = CL5_PURGE_MAX_PER_TRANSACTION; + dblcictx.rid2purge = cleaned_rid; + _cl5Iterate(cldb, _cl5PurgeRidOnEntry, &dblcictx, PR_FALSE); - /* - * Check every changelog entry for the cleaned rid - */ - rc = _cl5PurgeGetFirstEntry(cldb, &entry, &iterator, txnid, first_pass?0:cleaned_rid, &key); - first_pass = 0; - while (rc == CL5_SUCCESS && !slapi_is_shutting_down()) { - /* - * Store the new starting key - we need this starting key in case - * we run out of locks and have to start the transaction over. - */ - slapi_ch_free_string(&starting_key); - starting_key = slapi_ch_strdup((char *)key.data); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, + "_cl5PurgeRID - Removed (%ld entries) that originated from rid (%d)\n", + dblcictx.changed.tot, cleaned_rid); +} - if (trimmed == 10000 || (batch_count && trimmed == batch_count)) { - /* - * Break out, and commit these deletes. Do not free the key, - * we need it for the next pass. - */ - cl5_operation_parameters_done(&op); - db_lock_retry_count = 0; /* reset the retry count */ - break; - } - if (op.csn) { - csn_rid = csn_get_replicaid(op.csn); - if (csn_rid == cleaned_rid) { - rc = _cl5CurrentDeleteEntry(iterator); - if (rc != CL5_SUCCESS) { - /* log error */ - cl5_operation_parameters_done(&op); - if (rc == CL5_DB_LOCK_ERROR) { - /* - * Ran out of locks, need to restart the transaction. - * Reduce the the batch count and reset the key to - * the starting point - */ - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5PurgeRID - Ran out of db locks deleting entry. " - "Reduce the batch value and restart.\n"); - batch_count = trimmed - 10; - if (batch_count < 10) { - batch_count = 10; - } - trimmed = 0; - slapi_ch_free(&(key.data)); - key.data = starting_key; - starting_key = NULL; - db_lock_retry_count++; - break; - } else { - /* fatal error */ - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Fatal error (%d)\n", rc); - slapi_ch_free(&(key.data)); - finished = 1; - break; - } - } - trimmed++; - } - } - slapi_ch_free(&(key.data)); - cl5_operation_parameters_done(&op); +/* + * _cl5TrimReplica helper: dblayer_cursor_iterate callback. + * Returns: + * DBI_RC_SUCCESS to iterate on next entry + * DBI_RC_NOTFOUND to stop iteration with DBI_RC_SUCCESS code + * other DBI_RC_ code to stop iteration with that error code. + */ +int +_cl5TrimEntry(dbi_val_t *key, dbi_val_t *data, void *ctx) +{ + DBLCI_CTX *dblcictx = ctx; + Replica *r = dblcictx->r; + time_t entrytime = 0; + ReplicaId rid = 0; + int rc = 0; - rc = _cl5PurgeGetNextEntry(&entry, iterator, &key); - if (rc == CL5_DB_LOCK_ERROR) { - /* - * Ran out of locks, need to restart the transaction. - * Reduce the the batch count and reset the key to the starting - * point. - */ - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Ran out of db locks getting the next entry. " - "Reduce the batch value and restart.\n"); - batch_count = trimmed - 10; - if (batch_count < 10) { - batch_count = 10; - } - trimmed = 0; - cl5_operation_parameters_done(&op); - slapi_ch_free(&(key.data)); - key.data = starting_key; - starting_key = NULL; - db_lock_retry_count++; - break; - } - } + rc = _cl5CICbInit(key, data, dblcictx); + if (rc != DBI_RC_SUCCESS) { + return rc; + } - if (rc == CL5_NOTFOUND) { - /* Scanned the entire changelog, we're done */ - finished = 1; + if (cl5HelperEntry(NULL, &dblcictx->csn) == PR_TRUE) { + return DBI_RC_SUCCESS; + } + /* Get the operation time without decoding the whole operation */ + rc = cl5DBData2EntryTime(data->data, &entrytime); + if (rc != CL5_SUCCESS) { + return DBI_RC_OTHER; + } + if (dblcictx->numToTrim <= 0 && + _cl5CanTrim(entrytime, &dblcictx->numToTrim, r, &dblcictx->cldb->clConf) == PR_FALSE) { + /* trimming is complete */ + dblcictx->finished = PR_TRUE; + return DBI_RC_NOTFOUND; + } + if (ruv_covers_csn_strict(dblcictx->ruv, &dblcictx->csn)) { + /* Lets remove the entry */ + rc = _cl5CICbRemoveEntry(dblcictx, __FUNCTION__); + if (rc != DBI_RC_SUCCESS) { + return rc; } - - /* Destroy the iterator before we finish with the txn */ - cl5DestroyIterator(iterator); - - /* - * Commit or abort the txn + if (dblcictx->numToTrim > 0) + (dblcictx->numToTrim)--; + /* We should not update the changelog purge ruv with a deleted csn + * so lets us mark the rid to update the purge ruv on a second phase */ - if (rc == CL5_SUCCESS || rc == CL5_NOTFOUND) { - rc = TXN_COMMIT(cldb, txnid); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Failed to commit transaction; db error - %d %s. " - "Changelog was not completely purged of rid (%d)\n", - rc, dblayer_strerror(rc), cleaned_rid); - break; - } else if (finished) { - /* We're done */ - totalTrimmed += trimmed; - break; - } else { - /* Not done yet */ - totalTrimmed += trimmed; - } + rid = csn_get_replicaid(&dblcictx->csn); + _cl5GetRidInfo(dblcictx, rid, PR_TRUE); + } else { /* ruv_covers_csn_strict */ + /* The changelog DB is time ordered. If we can not trim + * a CSN, we will not be allowed to trim the rest of the + * CSNs generally. However, the maxcsn of each replica ID + * is always kept in the changelog as an anchor for + * replaying future changes. We have to skip those anchor + * CSNs, otherwise a non-active replica ID could block + * the trim forever. + */ + CSN *maxcsn = NULL; + ruv_get_largest_csn_for_replica(dblcictx->ruv, rid, &maxcsn); + rc = csn_compare(&dblcictx->csn, maxcsn); + if (maxcsn) + csn_free(&maxcsn); + if (rc) { + /* csn is not anchor CSN */ + dblcictx->finished = PR_TRUE; + return DBI_RC_NOTFOUND; } else { - rc = TXN_ABORT(cldb, txnid); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Failed to abort transaction; db error - %d %s. " - "Changelog was not completely purged of rid (%d)\n", - rc, dblayer_strerror(rc), cleaned_rid); - } - if (batch_count == 0) { - /* This was not a retry. Fatal error, break out */ - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5PurgeRID - Changelog was not purged of rid (%d)\n", - cleaned_rid); - break; - } + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, + "_cl5TrimReplica - Changelog purge skipped anchor csn %s\n", + (char*)key->data); + return DBI_RC_SUCCESS; } } - slapi_ch_free_string(&starting_key); - - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5PurgeRID - Removed (%ld entries) that originated from rid (%d)\n", - totalTrimmed, cleaned_rid); + return DBI_RC_SUCCESS; } - -#define CL5_TRIM_MAX_PER_TRANSACTION 10 - -static void -_cl5TrimReplica(Replica *r) +/* + * _cl5TrimReplica helper: dblayer_cursor_iterate callback. + * Update the purge ruv + * Returns: + * DBI_RC_SUCCESS to iterate on next entry + * DBI_RC_NOTFOUND to stop iteration with DBI_RC_SUCCESS code + * other DBI_RC_ code to stop iteration with that error code. + */ +int +_cl5TrimUpdateRuv(dbi_val_t *key, dbi_val_t *data, void *ctx) { - dbi_txn_t *txnid; - RUV *ruv = NULL; - CL5Entry entry; - slapi_operation_parameters op = {0}; - ReplicaId csn_rid; - void *it; - int finished = 0, totalTrimmed = 0, count; - PRBool abort; - char strCSN[CSN_STRSIZE]; - int rc; - long numToTrim; - - cldb_Handle *cldb = replica_get_cl_info(r); - - if (!_cl5CanTrim ((time_t)0, &numToTrim, r, &cldb->clConf) ) { - return; - } + DBLCI_CTX *dblcictx = ctx; + RID_INFO *ridinfo = NULL; + ReplicaId rid = 0; + int rc = 0; - /* construct the ruv up to which we can purge */ - rc = _cl5GetRUV2Purge2(r, &ruv); - if (rc != CL5_SUCCESS || ruv == NULL) { - return; + rc = _cl5CICbInit(key, data, dblcictx); + if (rc != DBI_RC_SUCCESS) { + return rc; } - - entry.op = &op; - while (!finished && !slapi_is_shutting_down()) { - it = NULL; - count = 0; - txnid = NULL; - abort = PR_FALSE; - - /* DB txn lock accessed pages until the end of the transaction. */ - - rc = TXN_BEGIN(cldb, NULL, &txnid, 0); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5TrimReplica - Failed to begin transaction; db error - %d %s\n", - rc, dblayer_strerror(rc)); - break; + rid = csn_get_replicaid(&dblcictx->csn); + ridinfo = _cl5GetRidInfo(dblcictx, rid, PR_FALSE); + if (ridinfo) { + rc = _cl5UpdateRUV(dblcictx->cldb, &dblcictx->csn, PR_FALSE, PR_TRUE); + if (rc != CL5_SUCCESS) { + return rc; } - finished = _cl5GetFirstEntry(cldb, &entry, &it, txnid); - while (!finished && !slapi_is_shutting_down()) { - /* - * This change can be trimmed if it exceeds purge - * parameters and has been seen by all consumers. - */ - if (op.csn == NULL) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, "_cl5TrimReplica - " - "Operation missing csn, moving on to next entry.\n"); - cl5_operation_parameters_done(&op); - finished = _cl5GetNextEntry(&entry, it); - continue; - } - csn_rid = csn_get_replicaid(op.csn); - - if ((numToTrim > 0 || _cl5CanTrim(entry.time, &numToTrim, r, &cldb->clConf)) && - ruv_covers_csn_strict(ruv, op.csn)) { - rc = _cl5CurrentDeleteEntry(it); - if (rc == CL5_SUCCESS) { - rc = _cl5UpdateRUV(cldb, op.csn, PR_FALSE, PR_TRUE); - } - if (rc == CL5_SUCCESS) { - if (numToTrim > 0) - (numToTrim)--; - count++; - } else { - /* The above two functions have logged the error */ - abort = PR_TRUE; - } - } else { - /* The changelog DB is time ordered. If we can not trim - * a CSN, we will not be allowed to trim the rest of the - * CSNs generally. However, the maxcsn of each replica ID - * is always kept in the changelog as an anchor for - * replaying future changes. We have to skip those anchor - * CSNs, otherwise a non-active replica ID could block - * the trim forever. - */ - CSN *maxcsn = NULL; - ruv_get_largest_csn_for_replica(ruv, csn_rid, &maxcsn); - if (csn_compare(op.csn, maxcsn) != 0) { - /* op.csn is not anchor CSN */ - finished = 1; - } else { - if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5TrimReplica - Changelog purge skipped anchor csn %s\n", - csn_as_string(maxcsn, PR_FALSE, strCSN)); - } - - /* extra read to skip the current record */ - cl5_operation_parameters_done(&op); - finished = _cl5GetNextEntry(&entry, it); - } - if (maxcsn) - csn_free(&maxcsn); - } - cl5_operation_parameters_done(&op); - if (finished || abort || count >= CL5_TRIM_MAX_PER_TRANSACTION) { - /* If we reach CL5_TRIM_MAX_PER_TRANSACTION, - * we close the cursor, - * commit the transaction and restart a new transaction - */ - break; - } - finished = _cl5GetNextEntry(&entry, it); + /* Lets remove the rid from the list */ + dblcictx->nb_rids--; + if (dblcictx->nb_rids == 0) { + dblcictx->finished = PR_TRUE; + return DBI_RC_NOTFOUND; } - - /* MAB: We need to close the cursor BEFORE the txn commits/aborts. - * If we don't respect this order, we'll screw up the database, - * placing it in DB_RUNRECOVERY mode - */ - cl5DestroyIterator(it); - - if (abort) { - finished = 1; - rc = TXN_ABORT(cldb, txnid); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5TrimReplica - Failed to abort transaction; db error - %d %s\n", - rc, dblayer_strerror(rc)); - } - } else { - rc = TXN_COMMIT(cldb, txnid); - if (rc != 0) { - finished = 1; - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5TrimReplica - Failed to commit transaction; db error - %d %s\n", - rc, dblayer_strerror(rc)); - } else { - totalTrimmed += count; - } + for (size_t i = ridinfo-dblcictx->rids; i <= dblcictx->nb_rids; i++) { + dblcictx->rids[i] = dblcictx->rids[i+1]; } + } + return DBI_RC_SUCCESS; +} - } /* While (!finished) */ +void +_cl5TrimReplica(Replica *r) +{ + DBLCI_CTX dblcictx = {0}; + int rc = CL5_SUCCESS; - if (ruv) - ruv_destroy(&ruv); + cldb_Handle *cldb = replica_get_cl_info(r); + if (!_cl5CanTrim ((time_t)0, &dblcictx.numToTrim, r, &cldb->clConf) ) { + return; + } - if (totalTrimmed) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5TrimReplica - Trimmed %d changes from the changelog\n", - totalTrimmed); + /* construct the ruv up to which we can trim */ + rc = _cl5GetRUV2Purge2(r, &dblcictx.ruv); + if (rc != CL5_SUCCESS || dblcictx.ruv == NULL) { + return; + } + dblcictx.r = r; + dblcictx.seen.nbmax = CL5_TRIM_MAX_LOOKUP_PER_TRANSACTION; + dblcictx.changed.nbmax = CL5_TRIM_MAX_PER_TRANSACTION; + rc = _cl5Iterate(cldb, _cl5TrimEntry, &dblcictx, PR_FALSE); + ruv_destroy(&dblcictx.ruv); + rc = _cl5Iterate(cldb, _cl5TrimUpdateRuv, &dblcictx, PR_TRUE); + slapi_ch_free((void**)&dblcictx.rids); + + if (dblcictx.changed.tot) { + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5TrimReplica - Trimmed %ld changes from the changelog\n", + dblcictx.changed.tot); } } @@ -2846,7 +2876,7 @@ _cl5ReadRUV (cldb_Handle *cldb, PRBool purge) goto done; case DBI_RC_NOTFOUND: /* RUV is lost - need to construct */ - rc = _cl5ConstructRUV(cldb, purge); + rc = CL5_NOTFOUND; goto done; default: @@ -2863,6 +2893,24 @@ done: return rc; } +/* Read changelog RUUV and purge RUV. Rebuild them if needed */ +int +_cl5ReadRUVs (cldb_Handle *cldb) +{ + int rc = _cl5ReadRUV(cldb, PR_TRUE); + if (rc == CL5_SUCCESS) { + rc = _cl5ReadRUV(cldb, PR_FALSE); + } + if (rc == CL5_NOTFOUND) { + rc = _cl5ConstructRUVs(cldb); + } + if (rc == CL5_SUCCESS) { + rc = _cl5GetEntryCount(cldb); + } + return rc; +} + + static int _cl5WriteRUV (cldb_Handle *cldb, PRBool purge) { @@ -2923,87 +2971,113 @@ _cl5WriteRUV (cldb_Handle *cldb, PRBool purge) } } -/* This is a very slow process since we have to read every changelog entry. - Hopefully, this function is not called too often */ -static int -_cl5ConstructRUV (cldb_Handle *cldb, PRBool purge) +/* _cl5ConstructRUVs helper: Action callback to build DBLCI_CTX */ +int +_cl5GenRUVInfo(dbi_val_t *key, dbi_val_t *data, void *ctx) { - int rc; - CL5Entry entry; - void *iterator = NULL; - slapi_operation_parameters op = {0}; - ReplicaId rid; + DBLCI_CTX *dblcictx = ctx; + ReplicaId rid = 0; + RID_INFO *ridinfo = NULL; + CSN csn = {0}; + int rc = _cl5CICbInit(key, data, dblcictx); + if (rc != DBI_RC_SUCCESS) { + return rc; + } + rid = csn_get_replicaid(&dblcictx->csn); + if (cl5HelperEntry(NULL, &dblcictx->csn) == PR_TRUE) { + return DBI_RC_SUCCESS; + } + if (is_cleaned_rid(rid)) { + /* skip this entry as the rid is invalid */ + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5GenRUVInfo - Skipping entry because its csn contains a cleaned rid(%d)\n", + rid); + return DBI_RC_SUCCESS; + } + /* Lets update min and max csn for the rid. + * As the db ensure that the csn are sorted, the first csn after ridinfo get created is the min + * and csn is the current max + */ + ridinfo = _cl5GetRidInfo(dblcictx, rid, PR_TRUE); + if (ridinfo->new == 1) { + ridinfo->new = 0; + ridinfo->mincsn = csn; + } + ridinfo->maxcsn = csn; + return DBI_RC_SUCCESS; +} +/* Walk every changelog records to find min and max csns for each rids then update changelog RUVs */ +int +_cl5ConstructRUVs (cldb_Handle *cldb) +{ /* construct the RUV */ - if (purge) - rc = ruv_init_new(cldb->ident, 0, NULL, &cldb->purgeRUV); - else - rc = ruv_init_new(cldb->ident, 0, NULL, &cldb->maxRUV); + DBLCI_CTX dblcictx = {0}; + char mincsnstr[CSN_STRSIZE] = ""; + char maxcsnstr[CSN_STRSIZE] = ""; + int rc = ruv_init_new(cldb->ident, 0, NULL, &cldb->purgeRUV); + if (rc != RUV_SUCCESS) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Failed to initialize %s RUV for file %s; ruv error - %d\n", - purge ? "purge" : "upper bound", cldb->ident, rc); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Failed to initialize purges RUV for file %s; ruv error - %d\n", + cldb->ident, rc); + return CL5_RUV_ERROR; + } + rc = ruv_init_new(cldb->ident, 0, NULL, &cldb->maxRUV); + if (rc != RUV_SUCCESS) { + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Failed to initialize upper bound RUV for file %s; ruv error - %d\n", + cldb->ident, rc); return CL5_RUV_ERROR; } slapi_log_err(SLAPI_LOG_NOTICE, repl_plugin_name_cl, - "_cl5ConstructRUV - Rebuilding the replication changelog RUV, " + "_cl5ConstructRUVs - Rebuilding the replication changelog RUV, " "this may take several minutes...\n"); - entry.op = &op; - rc = _cl5GetFirstEntry(cldb, &entry, &iterator, NULL); - while (rc == CL5_SUCCESS) { - if (op.csn) { - rid = csn_get_replicaid(op.csn); - } else { - slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Operation missing csn, moving on to next entry.\n"); - cl5_operation_parameters_done(&op); - rc = _cl5GetNextEntry(&entry, iterator); - continue; - } - if (is_cleaned_rid(rid)) { - /* skip this entry as the rid is invalid */ - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Skipping entry because its csn contains a cleaned rid(%d)\n", - rid); - cl5_operation_parameters_done(&op); - rc = _cl5GetNextEntry(&entry, iterator); - continue; - } - if (purge) - rc = ruv_set_csns_keep_smallest(cldb->purgeRUV, op.csn); - else - rc = ruv_set_csns(cldb->maxRUV, op.csn, NULL); - - cl5_operation_parameters_done(&op); - if (rc != RUV_SUCCESS) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUV - " - "Failed to update %s RUV for file %s; ruv error - %d\n", - purge ? "purge" : "upper bound", cldb->ident, rc); - rc = CL5_RUV_ERROR; - continue; - } - - rc = _cl5GetNextEntry(&entry, iterator); - } - - cl5_operation_parameters_done(&op); - - if (iterator) - cl5DestroyIterator(iterator); - + /* + * No specific dblcictx initialization has the changelog is starting, we may afford to + * have a single txn + */ + rc = _cl5Iterate(cldb, _cl5GenRUVInfo, &dblcictx, PR_TRUE); if (rc == CL5_NOTFOUND) { + /* Now that we have the min and max csn for each rids, it is time to update the RUVs */ rc = CL5_SUCCESS; - } else { - if (purge) - ruv_destroy(&cldb->purgeRUV); - else - ruv_destroy(&cldb->maxRUV); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Found %d replicas in %s changelog file.\n", + dblcictx.nb_rids, cldb->ident); + for (size_t i=0; i<dblcictx.nb_rids; i++) { + rc = ruv_set_csns(cldb->maxRUV, &dblcictx.rids[i].maxcsn, NULL); + if (rc != RUV_SUCCESS) { + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Failed to update upper bound RUV for file %s; ruv error - %d\n", + cldb->ident, rc); + rc = CL5_DB_ERROR; + break; + } + rc = ruv_set_csns(cldb->purgeRUV, &dblcictx.rids[i].mincsn, NULL); + if (rc != RUV_SUCCESS) { + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Failed to update purge RUV for file %s; ruv error - %d\n", + cldb->ident, rc); + rc = CL5_DB_ERROR; + break; + } + csn_as_string(&dblcictx.rids[i].maxcsn, PR_FALSE, maxcsnstr); + csn_as_string(&dblcictx.rids[i].mincsn, PR_FALSE, mincsnstr); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5ConstructRUVs - " + "Replica id: %d mincsn: %s maxcsn: %s\n", + dblcictx.rids[i].rid, mincsnstr, maxcsnstr); + } + } + slapi_ch_free((void**)&dblcictx.rids); + if (rc != RUV_SUCCESS) { + ruv_destroy(&cldb->purgeRUV); + ruv_destroy(&cldb->maxRUV); + rc = CL5_DB_ERROR; } slapi_log_err(SLAPI_LOG_NOTICE, repl_plugin_name_cl, - "_cl5ConstructRUV - Rebuilding replication changelog RUV complete. Result %d (%s)\n", + "_cl5ConstructRUVs - Rebuilding replication changelog RUV complete. Result %d (%s)\n", rc, rc ? "Failed to rebuild changelog RUV" : "Success"); return rc; @@ -3161,9 +3235,7 @@ cl5NotifyRUVChange(Replica *replica) ruv_destroy(&cldb->purgeRUV); cldb->ident = ruv_get_replica_generation ((RUV*)object_get_data (ruv_obj)); - _cl5ReadRUV(cldb, PR_TRUE); - _cl5ReadRUV(cldb, PR_FALSE); - _cl5GetEntryCount(cldb); + rc = _cl5ReadRUVs(cldb); pthread_mutex_unlock(&(cldb->clLock)); object_release(ruv_obj); @@ -3716,180 +3788,6 @@ _cl5WriteOperation(cldb_Handle *cldb, const slapi_operation_parameters *op) return _cl5WriteOperationTxn(cldb, op, NULL); } -static int -_cl5GetFirstEntry(cldb_Handle *cldb, CL5Entry *entry, void **iterator, dbi_txn_t *txnid) -{ - int rc; - dbi_cursor_t cursor = {0}; - dbi_val_t key = {0}, data = {0}; - CL5Iterator *it; - - PR_ASSERT(entry && iterator); - - /* create cursor */ - rc = dblayer_new_cursor(cldb->be, cldb->db, txnid, &cursor); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5GetFirstEntry - Failed to create cursor; db error - %d %s\n", rc, dblayer_strerror(rc)); - rc = CL5_DB_ERROR; - goto done; - } - - dblayer_value_init(cldb->be, &key); - dblayer_value_init(cldb->be, &data); - while ((rc = dblayer_cursor_op(&cursor, DBI_OP_NEXT, &key, &data)) == 0) { - /* skip service entries */ - if (cl5HelperEntry((char *)key.data, NULL)) { - continue; - } - - /* format entry */ - rc = cl5DBData2Entry(data.data, data.size, entry, cldb->clcrypt_handle); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name_cl, - "_cl5GetFirstOperation - Failed to format entry: %d\n", rc); - goto done; - } - - it = (CL5Iterator *)slapi_ch_malloc(sizeof(CL5Iterator)); - it->cursor = cursor; - it->it_cldb = cldb; - *(CL5Iterator **)iterator = it; - - dblayer_value_free(cldb->be, &key); - dblayer_value_free(cldb->be, &data); - return CL5_SUCCESS; - } - /* walked of the end of the file */ - if (rc == DBI_RC_NOTFOUND) { - rc = CL5_NOTFOUND; - goto done; - } - - /* db error occured while iterating */ - /* On this path, the condition "rc != 0" cannot be false */ - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5GetFirstEntry - Failed to get entry; db error - %d %s\n", - rc, dblayer_strerror(rc)); - rc = CL5_DB_ERROR; - -done: - /* error occured */ - /* - * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim - * Even when db->c_get() does not return success, memory may have been - * allocated in the dbi_val_t. This seems to happen when DB_dbi_val_t_MALLOC was set, - * the data being retrieved is larger than the page size, and we got - * DBI_RC_RETRY. libdb allocates the memory and then finds itself - * deadlocked trying to go through the overflow page list. It returns - * DBI_RC_RETRY which we've assumed meant that no memory was allocated - * for the dbi_val_t. - * - * The following slapi_ch_free frees the memory only when the value is - * non NULL, which is true if the situation described above occurs. - */ - dblayer_value_free(cldb->be, &key); - dblayer_value_free(cldb->be, &data); - - /* We didn't success in assigning this cursor to the iterator, - * so we need to free the cursor here */ - dblayer_cursor_op(&cursor, DBI_OP_CLOSE, NULL, NULL); - - return rc; -} - -static int -_cl5GetNextEntry(CL5Entry *entry, void *iterator) -{ - int rc; - CL5Iterator *it; - dbi_val_t key = {0}, data = {0}; - cldb_Handle *cldb; - - PR_ASSERT(entry && iterator); - - it = (CL5Iterator *)iterator; - cldb = it->it_cldb; - - dblayer_value_init(cldb->be, &key); - dblayer_value_init(cldb->be, &data); - while ((rc = dblayer_cursor_op(&it->cursor, DBI_OP_NEXT, &key, &data)) == 0) { - if (cl5HelperEntry((char *)key.data, NULL)) { - continue; - } - - /* format entry */ - rc = cl5DBData2Entry(data.data, data.size, entry, cldb->clcrypt_handle); - if (rc != 0) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5GetNextEntry - Failed to format entry: %d\n", rc); - } - - dblayer_value_free(cldb->be, &key); - dblayer_value_free(cldb->be, &data); - return rc; - } - /* - * Bug 430172 - memory leaks after db "get" deadlocks, e.g. in CL5 trim - * Even when db->c_get() does not return success, memory may have been - * allocated in the dbi_val_t. This seems to happen when DB_dbi_val_t_MALLOC was set, - * the data being retrieved is larger than the page size, and we got - * DBI_RC_RETRY. libdb allocates the memory and then finds itself - * deadlocked trying to go through the overflow page list. It returns - * DBI_RC_RETRY which we've assumed meant that no memory was allocated - * for the dbi_val_t. - * - * The following slapi_ch_free frees the memory only when the value is - * non NULL, which is true if the situation described above occurs. - */ - dblayer_value_free(cldb->be, &key); - dblayer_value_free(cldb->be, &data); - - /* walked of the end of the file or entry is out of range */ - if (rc == 0 || rc == DBI_RC_NOTFOUND) { - return CL5_NOTFOUND; - } - - /* cursor operation failed */ - slapi_log_err(rc == CL5_DB_LOCK_ERROR ? SLAPI_LOG_REPL : SLAPI_LOG_ERR, - repl_plugin_name_cl, - "_cl5GetNextEntry - Failed to get entry; db error - %d %s\n", - rc, dblayer_strerror(rc)); - - return rc; -} - -static int -_cl5CurrentDeleteEntry(void *iterator) -{ - int rc; - CL5Iterator *it; - cldb_Handle *cldb; - - PR_ASSERT(iterator); - - it = (CL5Iterator *)iterator; - - rc = dblayer_cursor_op(&it->cursor,DBI_OP_DEL, NULL, NULL); - - if (rc == 0) { - /* decrement entry count */ - cldb = it->it_cldb; - PR_AtomicDecrement(&cldb->entryCount); - return CL5_SUCCESS; - } else { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5CurrentDeleteEntry - Failed, err=%d %s\n", - rc, dblayer_strerror(rc)); - /* - * We don't free(close) the cursor here, as the caller will free it by - * a call to cl5DestroyIterator. Freeing it here is a potential bug, - * as the cursor can't be referenced later once freed. - */ - return rc; - } -} - PRBool cl5HelperEntry(const char *csnstr, CSN *csnp) { @@ -3955,7 +3853,7 @@ _cl5PositionCursorForReplay(ReplicaId consumerRID, const RUV *consumerRuv, Repli cldb_Handle *cldb = replica_get_cl_info(replica); PR_ASSERT (consumerRuv && replica && iterator); - + csnStr[0] = '\0'; /* get supplier's RUV */ @@ -4294,63 +4192,66 @@ _cl5CheckMissingCSN(const CSN *csn, const RUV *supplierRuv, cldb_Handle *cldb) /* Helper functions that work with individual changelog files */ -static int -_cl5ExportFile(PRFileDesc *prFile, cldb_Handle *cldb) +/* + * _cl5PurgeRid helper: dblayer_cursor_iterate callback. + * Returns: + * DBI_RC_SUCCESS to iterate on next entry + * DBI_RC_NOTFOUND to stop iteration with DBI_RC_SUCCESS code + * other DBI_RC_ code to stop iteration with that error code. + */ +int +_cl5ExportEntry2File(dbi_val_t *key, dbi_val_t *data, void *ctx) { - int rc; - void *iterator = NULL; + DBLCI_CTX *dblcictx = ctx; slapi_operation_parameters op = {0}; - char *buff; - PRInt32 len, wlen; + cldb_Handle *cldb = dblcictx->cldb; CL5Entry entry = {0}; - - PR_ASSERT(prFile && cldb); - - if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) { - ruv_dump(cldb->purgeRUV, "clpurgeruv", prFile); - ruv_dump(cldb->maxRUV, "clmaxruv", prFile); + PRInt32 len, wlen; + char *buff; + int rc = _cl5CICbInit(key, data, dblcictx); + if (rc != DBI_RC_SUCCESS) { + return rc; } - slapi_write_buffer(prFile, "\n", strlen("\n")); - entry.op = &op; - rc = _cl5GetFirstEntry(cldb, &entry, &iterator, NULL); - while (rc == CL5_SUCCESS) { - rc = _cl5Operation2LDIF(&op, cldb->ident, &buff, &len); - if (rc != CL5_SUCCESS) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5ExportFile - Failed to convert operation to ldif\n"); - operation_parameters_done(&op); - break; - } - - wlen = slapi_write_buffer(prFile, buff, len); - slapi_ch_free((void **)&buff); + rc = cl5DBData2Entry(data->data, data->size, &entry, cldb->clcrypt_handle); + if (rc != DBI_RC_SUCCESS) { + return rc; + } + rc = _cl5Operation2LDIF(&op, cldb->ident, &buff, &len); + if (rc != CL5_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, + "_cl5ExportEntry2File - Failed to convert operation to ldif\n"); + } else { + wlen = slapi_write_buffer(dblcictx->exportFile, buff, len); + slapi_ch_free_string(&buff); if (wlen < len) { slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5ExportFile - Failed to write to ldif file\n"); + "_cl5ExportEntry2File - Failed to write to ldif file\n"); rc = CL5_SYSTEM_ERROR; - operation_parameters_done(&op); - break; } - - cl5_operation_parameters_done(&op); - - rc = _cl5GetNextEntry(&entry, iterator); } + operation_parameters_done(&op); + return rc; +} - cl5_operation_parameters_done(&op); - - if (iterator) - cl5DestroyIterator(iterator); +static int +_cl5ExportFile(PRFileDesc *prFile, cldb_Handle *cldb) +{ + DBLCI_CTX dblcictx = {0}; + int rc = CL5_SUCCESS; + PR_ASSERT(prFile && cldb); - if (rc != CL5_NOTFOUND) { - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name_cl, - "_cl5ExportFile - Failed to retrieve changelog entry\n"); - } else { - rc = CL5_SUCCESS; + if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) { + ruv_dump(cldb->purgeRUV, "clpurgeruv", prFile); + ruv_dump(cldb->maxRUV, "clmaxruv", prFile); } + slapi_write_buffer(prFile, "\n", strlen("\n")); - return rc; + dblcictx.seen.nbmax = CL5_PURGE_MAX_LOOKUP_PER_TRANSACTION; + dblcictx.exportFile = prFile; + rc = _cl5Iterate(cldb, _cl5ExportEntry2File, &dblcictx, PR_TRUE); + + return (rc == CL5_NOTFOUND) ? CL5_SUCCESS : rc; } static char * @@ -4379,7 +4280,7 @@ _cl5WriteReplicaRUV(Replica *r, void *arg) { int rc = 0; cldb_Handle *cldb = replica_get_cl_info(r); - + if (NULL == cldb) { /* TBD should this really happen, do we need an error msg */ return rc; @@ -4417,9 +4318,9 @@ cl5Import(Slapi_PBlock *pb) "cl5Export - Importing changelog\n"); /* TBD - * as in cl5Export + * as in cl5Export * get ldif dir from pblock - * generate cl ldif name + * generate cl ldif name * call clImportLDIF */ return 0; diff --git a/ldap/servers/plugins/replication/cl5_api.h b/ldap/servers/plugins/replication/cl5_api.h index b0ab091f4..a690eee37 100644 --- a/ldap/servers/plugins/replication/cl5_api.h +++ b/ldap/servers/plugins/replication/cl5_api.h @@ -99,7 +99,9 @@ enum CL5_PURGED_DATA, /* requested data has been purged */ CL5_MISSING_DATA, /* data should be in the changelog, but is missing */ CL5_UNKNOWN_ERROR, /* unclassified error */ - CL5_IGNORE_OP /* ignore this updated - used by CLEANALLRUV task */ + CL5_IGNORE_OP, /* ignore this updated - used by CLEANALLRUV task */ + CL5_DB_RETRY, /* Retryable database error */ + CL5_LAST_ERROR_CODE /* Should always be last in this enum */ }; /***** Module APIs *****/ diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c index b988a9757..8f847f418 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_config.c @@ -136,6 +136,7 @@ int bdb_init(struct ldbminfo *li, config_info *config_array) priv->dblayer_get_db_suffix_fn = &bdb_public_get_db_suffix; priv->dblayer_compact_fn = &bdb_public_dblayer_compact; priv->dblayer_dbi_db_remove_fn = &bdb_public_delete_db; + priv->dblayer_cursor_iterate_fn = &bdb_dblayer_cursor_iterate; bdb_fake_priv = *priv; /* Copy the callbaks for bdb_be() */ return 0; diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c index a71912731..7016a0b7a 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c @@ -7161,3 +7161,53 @@ bdb_public_delete_db(backend *be, dbi_db_t *db) bdb_close_file((DB**)&db); return unlink(dbName); } + +int +bdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, dbi_iterate_cb_t *action_cb, + const dbi_val_t *startingkey, void *ctx) +{ + DBC *bdb_cur = (DBC*)cursor->cur; + DBT bdb_key = {0}; + DBT bdb_data = {0}; + dbi_val_t key = {0}; + dbi_val_t data = {0}; + int rc = 0; + + if (bdb_cur == NULL) { + return DBI_RC_INVALID; + } + + bdb_key.flags = DB_DBT_REALLOC; + bdb_data.flags = DB_DBT_REALLOC; + if (startingkey && startingkey->data && startingkey->size) { + bdb_key.data = slapi_ch_malloc(startingkey->size); + memcpy(bdb_key.data, startingkey->data, startingkey->size); + bdb_key.size = bdb_key.ulen = startingkey->size; + rc = bdb_cur->c_get(bdb_cur, &bdb_key, &bdb_data, DB_SET_RANGE); + } else { + rc = bdb_cur->c_get(bdb_cur, &bdb_key, &bdb_data, DB_FIRST); + } + while (rc == 0) { + key.data = bdb_key.data; + key.size = bdb_key.size; + data.data = bdb_data.data; + data.size = bdb_data.size; + rc = action_cb(&key, &data, ctx); + if (rc == DBI_RC_NOTFOUND) { + rc = DBI_RC_SUCCESS; + break; + } + rc = bdb_cur->c_get(bdb_cur, &bdb_key, &bdb_data, DB_NEXT); + } + if (rc == DB_NOTFOUND) { + rc = DBI_RC_NOTFOUND; + } else if (rc != DBI_RC_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, "bdb_dblayer_cursor_iterate", + "Database error while iterating a cursor ; db error - %d %s\n", + rc, db_strerror(rc)); + rc = bdb_map_error(__FUNCTION__, rc); + } + slapi_ch_free(&bdb_key.data); + slapi_ch_free(&bdb_data.data); + return rc; +} diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h index b1bcd0241..6e18db992 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.h @@ -226,6 +226,9 @@ int bdb_dse_conf_verify(struct ldbminfo *li, char *src_dir); int bdb_import_file_check_fn_t(ldbm_instance *inst); dbi_dbslist_t *bdb_list_dbs(const char *dbhome); int bdb_public_in_import(ldbm_instance *inst); +int bdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, + int (*action_cb)(dbi_val_t *key, dbi_val_t *data, void *ctx), + const dbi_val_t *startingkey, void *ctx); /* dbimpl helpers */ @@ -282,3 +285,5 @@ void bdb_index_producer(void *param); void bdb_upgradedn_producer(void *param); void bdb_import_foreman(void *param); void bdb_import_worker(void *param); + + diff --git a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_config.c b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_config.c index 17e2a804e..5b364cb43 100644 --- a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_config.c +++ b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_config.c @@ -188,6 +188,7 @@ int mdb_init(struct ldbminfo *li, config_info *config_array) priv->dblayer_clear_vlv_cache_fn = &dbmdb_public_clear_vlv_cache; priv->dblayer_dbi_db_remove_fn = &dbmdb_public_delete_db; priv->dblayer_idl_new_fetch_fn = &dbmdb_idl_new_fetch; + priv->dblayer_cursor_iterate_fn = &dbmdb_dblayer_cursor_iterate; dbmdb_fake_priv = *priv; /* Copy the callbaks for dbmdb_be() */ return 0; diff --git a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.c b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.c index afc2158e5..d8ca347cc 100644 --- a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.c +++ b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.c @@ -2933,3 +2933,48 @@ error: *flag_err = rc; return idl; } + +int +dbmdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, dbi_iterate_cb_t *action_cb, + const dbi_val_t *startingkey, void *ctx) +{ + MDB_cursor *mdb_cur = (MDB_cursor*)cursor->cur; + MDB_val mdb_key = {0}; + MDB_val mdb_data = {0}; + dbi_val_t key = {0}; + dbi_val_t data = {0}; + int rc = 0; + + if (mdb_cur == NULL) { + return DBI_RC_INVALID; + } + + if (startingkey && startingkey->data && startingkey->size) { + mdb_key.mv_data = startingkey->data; + mdb_key.mv_size = startingkey->size; + rc = MDB_CURSOR_GET(mdb_cur, &mdb_key, &mdb_data, MDB_SET_RANGE); + } else { + rc = MDB_CURSOR_GET(mdb_cur, &mdb_key, &mdb_data, MDB_FIRST); + } + while (rc == MDB_SUCCESS) { + key.data = mdb_key.mv_data; + key.size = mdb_key.mv_size; + data.data = mdb_data.mv_data; + data.size = mdb_data.mv_size; + rc = action_cb(&key, &data, ctx); + if (rc == DBI_RC_NOTFOUND) { + rc = DBI_RC_SUCCESS; + break; + } + rc = MDB_CURSOR_GET(mdb_cur, &mdb_key, &mdb_data, MDB_NEXT); + } + if (rc == MDB_NOTFOUND) { + rc = DBI_RC_NOTFOUND; + } else if (rc != DBI_RC_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, "dbmdb_dblayer_cursor_iterate", + "Database error while iterating a cursor ; db error - %d %s\n", + rc, mdb_strerror(rc)); + rc = dbmdb_map_error(__FUNCTION__, rc); + } + return rc; +} diff --git a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.h b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.h index 797c92e8b..ce46c08cb 100644 --- a/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.h +++ b/ldap/servers/slapd/back-ldbm/db-mdb/mdb_layer.h @@ -414,6 +414,10 @@ int dbmdb_show_stat(const char *dbhome, FILE *fout, FILE *ferr); int dbmdb_public_in_import(ldbm_instance *inst); const char *dbmdb_public_get_db_suffix(void); int dbmdb_public_delete_db(Slapi_Backend *be, dbi_db_t *db); +int dbmdb_dblayer_cursor_iterate(dbi_cursor_t *cursor, + int (*action_cb)(dbi_val_t *key, dbi_val_t *data, void *ctx), + const dbi_val_t *startingkey, void *ctx); + /* dbimpl helpers */ diff --git a/ldap/servers/slapd/back-ldbm/dbimpl.h b/ldap/servers/slapd/back-ldbm/dbimpl.h index ba0b310bb..6050e2354 100644 --- a/ldap/servers/slapd/back-ldbm/dbimpl.h +++ b/ldap/servers/slapd/back-ldbm/dbimpl.h @@ -116,6 +116,7 @@ typedef struct { } dbi_dbslist_t; struct attrinfo; +typedef int dbi_iterate_cb_t(dbi_val_t *key, dbi_val_t *data, void *ctx); /* * dbimpl.c Function prototypes are stored here instead of in @@ -163,6 +164,10 @@ int dblayer_private_close(Slapi_Backend **be, dbi_env_t **env, dbi_db_t **db); dbi_dbslist_t *dblayer_list_dbs(const char *dbimpl_name, const char *dbhome); int dblayer_db_remove(Slapi_Backend *be, dbi_db_t *db); int dblayer_show_statistics(const char *dbimpl_name, const char *dbhome, FILE *fout, FILE *ferr); +int dblayer_is_lmdb(Slapi_Backend *be); +int dblayer_cursor_iterate(dbi_cursor_t *cursor, + int (*action_cb)(dbi_val_t *key, dbi_val_t *data, void *ctx), + const dbi_val_t *startingkey, void *ctx); #endif /* DBIMPL_H_ */ diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index 2bd246aac..d5022cd5b 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -1395,3 +1395,32 @@ ldbm_back_compact(Slapi_Backend *be, PRBool just_changelog) return prv->dblayer_compact_fn(be, just_changelog); } + +int +dblayer_is_lmdb(Slapi_Backend *be) +{ + struct ldbminfo *li = (struct ldbminfo *)be->be_database->plg_private; + return (li->li_flags & LI_LMDB_IMPL); +} + +/* + * Iterate on the provided curor starting at startingkey (or first key if + * startingkey is NULL) and call action_cb for each records + * + * action_cb callback returns: + * DBI_RC_SUCCESS to iterate on next entry + * DBI_RC_NOTFOUND to stop iteration with DBI_RC_SUCCESS code + * other DBI_RC_ code to stop iteration with that error code. + */ +int dblayer_cursor_iterate(dbi_cursor_t *cursor, dbi_iterate_cb_t *action_cb, + const dbi_val_t *startingkey, void *ctx) +{ + struct ldbminfo *li = (struct ldbminfo *)cursor->be->be_database->plg_private; + int rc = -1; + if (!li) { + return rc; + } + dblayer_private *prv = (dblayer_private *)li->li_dblayer_private; + + return prv->dblayer_cursor_iterate_fn(cursor, action_cb, startingkey, ctx); +} diff --git a/ldap/servers/slapd/back-ldbm/dblayer.h b/ldap/servers/slapd/back-ldbm/dblayer.h index edd2d3d3f..c93a0957f 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.h +++ b/ldap/servers/slapd/back-ldbm/dblayer.h @@ -124,6 +124,8 @@ typedef int dblayer_clear_vlv_cache_fn_t(backend *be, dbi_txn_t *txn, dbi_db_t * typedef int dblayer_dbi_db_remove_fn_t(backend *be, dbi_db_t *db); typedef IDList *dblayer_idl_new_fetch_fn_t(backend *be, dbi_db_t *db, dbi_val_t *inkey, dbi_txn_t *txn, struct attrinfo *a, int *flag_err, int allidslimit); +typedef int dblayer_cursor_iterate_fn_t(dbi_cursor_t *cursor, dbi_iterate_cb_t *action_cb, + const dbi_val_t *startingkey, void *ctx); struct dblayer_private { @@ -207,6 +209,7 @@ struct dblayer_private dblayer_clear_vlv_cache_fn_t *dblayer_clear_vlv_cache_fn; dblayer_dbi_db_remove_fn_t *dblayer_dbi_db_remove_fn; dblayer_idl_new_fetch_fn_t *dblayer_idl_new_fetch_fn; + dblayer_cursor_iterate_fn_t *dblayer_cursor_iterate_fn; }; #define DBLAYER_PRIV_SET_DATA_DIR 0x1 diff --git a/src/lib389/lib389/topologies.py b/src/lib389/lib389/topologies.py index d44299c5b..2b5e3db31 100644 --- a/src/lib389/lib389/topologies.py +++ b/src/lib389/lib389/topologies.py @@ -18,7 +18,7 @@ from lib389 import DirSrv from lib389.utils import generate_ds_params, is_fips from lib389.mit_krb5 import MitKrb5 from lib389.saslmap import SaslMappings -from lib389.replica import ReplicationManager, Replicas +from lib389.replica import Agreements, ReplicationManager, Replicas from lib389.nss_ssl import NssSsl from lib389._constants import * from lib389.cli_base import LogCapture @@ -525,5 +525,15 @@ def topology_m1h1c1(request): topo_roles = {ReplicaRole.SUPPLIER: 1, ReplicaRole.HUB: 1, ReplicaRole.CONSUMER: 1} topology = create_topology(topo_roles, request=request) + # Since topology implements timeout, create_topology supports hub + # but hub and suppliers are fully meshed while historically this topology + # did not have hub->master agreement. + # ==> we must remove hub->master agmt that breaks some test (like promote_demote) + supplier = topology.ms["supplier1"] + hub = topology.hs["hub1"] + for agmt in Agreements(hub).list(): + if supplier.port == agmt.get_attr_val_int("nsDS5ReplicaPort"): + agmt.delete() + topology.logcap = LogCapture() return topology
0
c79c1ebbd1590b4559d4926539ccde7c15b6328f
389ds/389-ds-base
Issue 6619 - test_dblib_migration fails on RHEL10 (#6620) * Issue 6619 - test_dblib_migration fails on RHEL10 Test test_dblib_migration fails on RHEL10 because bdb is not supported. Test should be skipped in that case and libdb should provide a function to check if server can starts on bdb Issue: #6619 Reviewed by: @jchapma (Thanks!)
commit c79c1ebbd1590b4559d4926539ccde7c15b6328f Author: progier389 <[email protected]> Date: Wed Feb 19 19:11:11 2025 +0100 Issue 6619 - test_dblib_migration fails on RHEL10 (#6620) * Issue 6619 - test_dblib_migration fails on RHEL10 Test test_dblib_migration fails on RHEL10 because bdb is not supported. Test should be skipped in that case and libdb should provide a function to check if server can starts on bdb Issue: #6619 Reviewed by: @jchapma (Thanks!) diff --git a/dirsrvtests/tests/suites/clu/dsctl_dblib_test.py b/dirsrvtests/tests/suites/clu/dsctl_dblib_test.py index 141384bb4..4d5a54eee 100644 --- a/dirsrvtests/tests/suites/clu/dsctl_dblib_test.py +++ b/dirsrvtests/tests/suites/clu/dsctl_dblib_test.py @@ -13,7 +13,11 @@ import os import time from lib389._constants import DEFAULT_SUFFIX from lib389.backend import DatabaseConfig -from lib389.cli_ctl.dblib import (FakeArgs, dblib_bdb2mdb, dblib_mdb2bdb, dblib_cleanup) +from lib389.cli_ctl.dblib import ( + FakeArgs, + dblib_bdb2mdb, + dblib_cleanup, + is_bdb_supported) from lib389.idm.user import UserAccounts from lib389.replica import ReplicationManager from lib389.topologies import topology_m2 as topo_m2, topology_st as topo_st @@ -87,6 +91,7 @@ def _check_db(inst, log, impl): assert db_files == mdb_list [email protected](is_bdb_supported() is False, reason='This test requires bdb support') def test_dblib_migration(init_user): """ Verify dsctl dblib xxxxxxx sub commands (migration between bdb and lmdb) diff --git a/src/lib389/lib389/cli_ctl/dblib.py b/src/lib389/lib389/cli_ctl/dblib.py index 053a72d61..35f6e6986 100644 --- a/src/lib389/lib389/cli_ctl/dblib.py +++ b/src/lib389/lib389/cli_ctl/dblib.py @@ -51,7 +51,7 @@ class FakeArgs(dict): def get_bdb_impl_status(): backldbm = 'libback-ldbm' - bundledbdb_plugin = 'libback-ldbm' + bundledbdb_plugin = 'libback-bdb' robdb_symbol = 'bdbro_getcb_vector' libdb = 'libdb-' plgstrs = check_plugin_strings(backldbm, [bundledbdb_plugin, robdb_symbol, libdb]) @@ -70,6 +70,14 @@ def get_bdb_impl_status(): return BDB_IMPL_STATUS.UNKNOWN +def is_bdb_supported(read_write=True): + bdbok = [BDB_IMPL_STATUS.BUNDLED, BDB_IMPL_STATUS.STANDARD] + if not read_write: + # READ_MODE is ok too + bdbok.append(BDB_IMPL_STATUS.READ_ONLY) + return get_bdb_impl_status() in bdbok + + def get_ldif_dir(instance): """ Get the server's LDIF directory.
0
f1f75f664a0e26d944c01995dd45ec8c1116893d
389ds/389-ds-base
Bump version to 1.1.0 alpha 3 (1.1.0a3)
commit f1f75f664a0e26d944c01995dd45ec8c1116893d Author: Rich Megginson <[email protected]> Date: Tue Mar 20 18:46:45 2007 +0000 Bump version to 1.1.0 alpha 3 (1.1.0a3) diff --git a/configure b/configure index f21980e9a..8569144a4 100755 --- a/configure +++ b/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.59 for fedora-ds 1.1.0a2. +# Generated by GNU Autoconf 2.59 for fedora-ds 1.1.0a3. # # Report bugs to <http://bugzilla.redhat.com/>. # @@ -423,8 +423,8 @@ SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='fedora-ds' PACKAGE_TARNAME='fedora-ds' -PACKAGE_VERSION='1.1.0a2' -PACKAGE_STRING='fedora-ds 1.1.0a2' +PACKAGE_VERSION='1.1.0a3' +PACKAGE_STRING='fedora-ds 1.1.0a3' PACKAGE_BUGREPORT='http://bugzilla.redhat.com/' # Factoring default headers for most tests. @@ -954,7 +954,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures fedora-ds 1.1.0a2 to adapt to many kinds of systems. +\`configure' configures fedora-ds 1.1.0a3 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1020,7 +1020,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of fedora-ds 1.1.0a2:";; + short | recursive ) echo "Configuration of fedora-ds 1.1.0a3:";; esac cat <<\_ACEOF @@ -1197,7 +1197,7 @@ fi test -n "$ac_init_help" && exit 0 if $ac_init_version; then cat <<\_ACEOF -fedora-ds configure 1.1.0a2 +fedora-ds configure 1.1.0a3 generated by GNU Autoconf 2.59 Copyright (C) 2003 Free Software Foundation, Inc. @@ -1211,7 +1211,7 @@ cat >&5 <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by fedora-ds $as_me 1.1.0a2, which was +It was created by fedora-ds $as_me 1.1.0a3, which was generated by GNU Autoconf 2.59. Invocation command line was $ $0 $@ @@ -1857,7 +1857,7 @@ fi # Define the identity of the package. PACKAGE='fedora-ds' - VERSION='1.1.0a2' + VERSION='1.1.0a3' cat >>confdefs.h <<_ACEOF @@ -25527,7 +25527,7 @@ _ASBOX } >&5 cat >&5 <<_CSEOF -This file was extended by fedora-ds $as_me 1.1.0a2, which was +This file was extended by fedora-ds $as_me 1.1.0a3, which was generated by GNU Autoconf 2.59. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -25590,7 +25590,7 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ -fedora-ds config.status 1.1.0a2 +fedora-ds config.status 1.1.0a3 configured by $0, generated by GNU Autoconf 2.59, with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\" diff --git a/configure.ac b/configure.ac index 78e24e17d..138269042 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) # This version is the version returned by ns-slapd -v -AC_INIT([fedora-ds], [1.1.0a2], [http://bugzilla.redhat.com/]) +AC_INIT([fedora-ds], [1.1.0a3], [http://bugzilla.redhat.com/]) # AC_CONFIG_HEADER must be called right after AC_INIT. AC_CONFIG_HEADERS([config.h]) AM_INIT_AUTOMAKE([1.9 foreign subdir-objects]) diff --git a/ltmain.sh b/ltmain.sh index 06823e057..0223495a0 100644 --- a/ltmain.sh +++ b/ltmain.sh @@ -46,10 +46,16 @@ PACKAGE=libtool VERSION=1.5.22 TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)" -# See if we are running on zsh, and set the options which allow our -# commands through without removal of \ escapes. -if test -n "${ZSH_VERSION+set}" ; then +# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE). +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi # Check that we have a working $echo. @@ -105,12 +111,14 @@ esac # These must not be set unconditionally because not all systems understand # e.g. LANG=C (notably SCO). # We save the old values to restore during execute mode. -if test "${LC_ALL+set}" = set; then - save_LC_ALL="$LC_ALL"; LC_ALL=C; export LC_ALL -fi -if test "${LANG+set}" = set; then - save_LANG="$LANG"; LANG=C; export LANG -fi +for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test \"\${$lt_var+set}\" = set; then + save_$lt_var=\$$lt_var + $lt_var=C + export $lt_var + fi" +done # Make sure IFS has a sensible default lt_nl=' @@ -136,6 +144,8 @@ duplicate_deps=no preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" +extracted_archives= +extracted_serial=0 ##################################### # Shell function definitions: @@ -327,7 +337,17 @@ func_extract_archives () *) my_xabs=`pwd`"/$my_xlib" ;; esac my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'` - my_xdir="$my_gentop/$my_xlib" + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + extracted_serial=`expr $extracted_serial + 1` + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir="$my_gentop/$my_xlib_u" $show "${rm}r $my_xdir" $run ${rm}r "$my_xdir" @@ -758,6 +778,7 @@ if test -z "$show_help"; then *.f90) xform=f90 ;; *.for) xform=for ;; *.java) xform=java ;; + *.obj) xform=obj ;; esac libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` @@ -1138,8 +1159,9 @@ EOF for arg do case $arg in - -all-static | -static) - if test "X$arg" = "X-all-static"; then + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2 fi @@ -1147,12 +1169,20 @@ EOF dlopen_self=$dlopen_self_static fi prefer_static_libs=yes - else + ;; + -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built - fi + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac build_libtool_libs=no build_old_libs=yes break @@ -1712,7 +1742,7 @@ EOF continue ;; - -static) + -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects @@ -2490,7 +2520,9 @@ EOF if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && - { test "$prefer_static_libs" = no || test -z "$old_library"; }; then + { { test "$prefer_static_libs" = no || + test "$prefer_static_libs,$installed" = "built,yes"; } || + test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. @@ -3186,7 +3218,7 @@ EOF # which has an extra 1 added just for fun # case $version_type in - darwin|linux|osf|windows) + darwin|linux|osf|windows|none) current=`expr $number_major + $number_minor` age="$number_minor" revision="$number_revision" @@ -3410,11 +3442,11 @@ EOF fi # Eliminate all temporary directories. - for path in $notinst_path; do - lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"` - deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"` - dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"` - done +# for path in $notinst_path; do +# lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"` +# deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"` +# dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"` +# done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. @@ -3515,13 +3547,12 @@ EOF int main() { return 0; } EOF $rm conftest - $LTCC $LTCFLAGS -o conftest conftest.c $deplibs - if test "$?" -eq 0 ; then + if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then ldd_output=`ldd conftest` for i in $deplibs; do name=`expr $i : '-l\(.*\)'` # If $name is empty we are operating on a -L argument. - if test "$name" != "" && test "$name" -ne "0"; then + if test "$name" != "" && test "$name" != "0"; then if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) @@ -3560,9 +3591,7 @@ EOF # If $name is empty we are operating on a -L argument. if test "$name" != "" && test "$name" != "0"; then $rm conftest - $LTCC $LTCFLAGS -o conftest conftest.c $i - # Did it work? - if test "$?" -eq 0 ; then + if $LTCC $LTCFLAGS -o conftest conftest.c $i; then ldd_output=`ldd conftest` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in @@ -3594,7 +3623,7 @@ EOF droppeddeps=yes $echo $echo "*** Warning! Library $i is needed by this library but I was not able to" - $echo "*** make it link in! You will probably need to install it or some" + $echo "*** make it link in! You will probably need to install it or some" $echo "*** library that it depends on before this library will be fully" $echo "*** functional. Installing it before continuing would be even better." fi @@ -4239,12 +4268,14 @@ EOF reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of - # -Wl from whole_archive_flag_spec + # -Wl from whole_archive_flag_spec and hope we can get by with + # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then - eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\" + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + reload_conv_objs=$reload_objs\ `$echo "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` else gentop="$output_objdir/${obj}x" generated="$generated $gentop" @@ -4692,16 +4723,16 @@ static const void *lt_preloaded_setup() { case $host in *cygwin* | *mingw* ) if test -f "$output_objdir/${outputname}.def" ; then - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP` else - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` fi ;; * ) - compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` ;; esac ;; @@ -4716,13 +4747,13 @@ static const void *lt_preloaded_setup() { # really was required. # Nullify the symbol file. - compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` - finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP` + finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP` fi if test "$need_relink" = no || test "$build_libtool_libs" != yes; then # Replace the output file specification. - compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` + compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$output"'%g' | $NL2SP` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. @@ -4809,7 +4840,7 @@ static const void *lt_preloaded_setup() { if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then - relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` + relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $SP2NL | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g' | $NL2SP` else # fast_install is set to needless relink_command= @@ -4846,7 +4877,7 @@ static const void *lt_preloaded_setup() { fi done relink_command="(cd `pwd`; $relink_command)" - relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP` fi # Quote $echo for shipping. @@ -5253,6 +5284,18 @@ EOF Xsed='${SED} -e 1s/^X//' sed_quote_subst='$sed_quote_subst' +# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE). +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi + # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH @@ -5395,7 +5438,7 @@ else ;; esac $echo >> $output "\ - \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\" + \$echo \"\$0: cannot exec \$program \$*\" exit $EXIT_FAILURE fi else @@ -5581,7 +5624,7 @@ fi\ done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" - relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` + relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP` if test "$hardcode_automatic" = yes ; then relink_command= fi @@ -5926,9 +5969,9 @@ relink_command=\"$relink_command\"" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. - relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%" | $NL2SP` else - relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP` fi $echo "$modename: warning: relinking \`$file'" 1>&2 @@ -6137,7 +6180,7 @@ relink_command=\"$relink_command\"" file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'` outputname="$tmpdir/$file" # Replace the output file specification. - relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` + relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g' | $NL2SP` $show "$relink_command" if $run eval "$relink_command"; then : @@ -6413,12 +6456,15 @@ relink_command=\"$relink_command\"" fi # Restore saved environment variables - if test "${save_LC_ALL+set}" = set; then - LC_ALL="$save_LC_ALL"; export LC_ALL - fi - if test "${save_LANG+set}" = set; then - LANG="$save_LANG"; export LANG - fi + for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + # Now prepare to actually exec the command. exec_cmd="\$cmd$args" @@ -6775,9 +6821,9 @@ The following components of LINK-COMMAND are treated specially: -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE - try to export only the symbols listed in SYMFILE + try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX - try to export only the symbols matching REGEX + try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened @@ -6791,9 +6837,11 @@ The following components of LINK-COMMAND are treated specially: -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries - -static do not do any dynamic linking of libtool libraries + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] - specify library version info [each variable defaults to 0] + specify library version info [each variable defaults to 0] All other options (arguments beginning with \`-') are ignored.
0
0c7ef560ae3f4641155a44509573b6f6dfff1caa
389ds/389-ds-base
Ticket 49008 v2: aborted operation can leave RUV in incorrect state Bug description: If a plugin operation succeeded, but the operation itself fails and is aborted the RUV is in an incorrect state (rolled up to the succesful plugin op) Fix Decription: Introduce a "primary_csn", this is the csn of the main operation, either a client operation or a replicated operation. csns generated by internal operations, eg by plugins are secondary csn. Maintain the primary csn in thread local data, like it is used for the agreement name (or txn stack): prim_csn. Extend the data structure of the pending list to keep prim_csn for each inserted csn If a csn is created or received check prim_csn: if it exists use it, if it doesn't exist set it when inserting a csn to the pending list pass the prim_csn when cancelling a csn, if it is the prim_csn also cancell all secondary csns when committing a csn, if it is not the primary csn, do nothing if it is the prim_csn trigger the pending list rollup, stop at the first not committed csn if the RID of the prim_csn is not the local RID also rollup the pending list for the local RID. Reviewed by: Thierry, Thanks
commit 0c7ef560ae3f4641155a44509573b6f6dfff1caa Author: Ludwig Krispenz <[email protected]> Date: Tue Jan 24 14:05:16 2017 +0100 Ticket 49008 v2: aborted operation can leave RUV in incorrect state Bug description: If a plugin operation succeeded, but the operation itself fails and is aborted the RUV is in an incorrect state (rolled up to the succesful plugin op) Fix Decription: Introduce a "primary_csn", this is the csn of the main operation, either a client operation or a replicated operation. csns generated by internal operations, eg by plugins are secondary csn. Maintain the primary csn in thread local data, like it is used for the agreement name (or txn stack): prim_csn. Extend the data structure of the pending list to keep prim_csn for each inserted csn If a csn is created or received check prim_csn: if it exists use it, if it doesn't exist set it when inserting a csn to the pending list pass the prim_csn when cancelling a csn, if it is the prim_csn also cancell all secondary csns when committing a csn, if it is not the primary csn, do nothing if it is the prim_csn trigger the pending list rollup, stop at the first not committed csn if the RID of the prim_csn is not the local RID also rollup the pending list for the local RID. Reviewed by: Thierry, Thanks diff --git a/ldap/servers/plugins/replication/csnpl.c b/ldap/servers/plugins/replication/csnpl.c index 7861b6d8c..4a0f5f5af 100644 --- a/ldap/servers/plugins/replication/csnpl.c +++ b/ldap/servers/plugins/replication/csnpl.c @@ -24,8 +24,9 @@ struct csnpl typedef struct _csnpldata { - PRBool committed; /* True if CSN committed */ - CSN *csn; /* The actual CSN */ + PRBool committed; /* True if CSN committed */ + CSN *csn; /* The actual CSN */ + const CSN *prim_csn; /* The primary CSN of an operation consising of multiple sub ops*/ } csnpldata; /* forward declarations */ @@ -103,7 +104,7 @@ void csnplFree (CSNPL **csnpl) * 1 if the csn has already been seen * -1 for any other kind of errors */ -int csnplInsert (CSNPL *csnpl, const CSN *csn) +int csnplInsert (CSNPL *csnpl, const CSN *csn, const CSN *prim_csn) { int rc; csnpldata *csnplnode; @@ -131,6 +132,7 @@ int csnplInsert (CSNPL *csnpl, const CSN *csn) csnplnode = (csnpldata *)slapi_ch_malloc(sizeof(csnpldata)); csnplnode->committed = PR_FALSE; csnplnode->csn = csn_dup(csn); + csnplnode->prim_csn = prim_csn; csn_as_string(csn, PR_FALSE, csn_str); rc = llistInsertTail (csnpl->csnList, csn_str, csnplnode); @@ -186,6 +188,57 @@ int csnplRemove (CSNPL *csnpl, const CSN *csn) return 0; } +int csnplRemoveAll (CSNPL *csnpl, const CSN *csn) +{ + csnpldata *data; + void *iterator; + + slapi_rwlock_wrlock (csnpl->csnLock); + data = (csnpldata *)llistGetFirst(csnpl->csnList, &iterator); + while (NULL != data) + { + if (csn_is_equal(data->csn, csn) || + csn_is_equal(data->prim_csn, csn)) { + csnpldata_free(&data); + data = (csnpldata *)llistRemoveCurrentAndGetNext(csnpl->csnList, &iterator); + } else { + data = (csnpldata *)llistGetNext (csnpl->csnList, &iterator); + } + } +#ifdef DEBUG + _csnplDumpContentNoLock(csnpl, "csnplRemoveAll"); +#endif + slapi_rwlock_unlock (csnpl->csnLock); + return 0; +} + + +int csnplCommitAll (CSNPL *csnpl, const CSN *csn) +{ + csnpldata *data; + void *iterator; + char csn_str[CSN_STRSIZE]; + + csn_as_string(csn, PR_FALSE, csn_str); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, + "csnplCommitALL: committing all csns for csn %s\n", csn_str); + slapi_rwlock_wrlock (csnpl->csnLock); + data = (csnpldata *)llistGetFirst(csnpl->csnList, &iterator); + while (NULL != data) + { + csn_as_string(data->csn, PR_FALSE, csn_str); + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, + "csnplCommitALL: processing data csn %s\n", csn_str); + if (csn_is_equal(data->csn, csn) || + csn_is_equal(data->prim_csn, csn)) { + data->committed = PR_TRUE; + } + data = (csnpldata *)llistGetNext (csnpl->csnList, &iterator); + } + slapi_rwlock_unlock (csnpl->csnLock); + return 0; +} + int csnplCommit (CSNPL *csnpl, const CSN *csn) { csnpldata *data; @@ -276,13 +329,12 @@ csnplRollUp(CSNPL *csnpl, CSN **first_commited) *first_commited = NULL; } data = (csnpldata *)llistGetFirst(csnpl->csnList, &iterator); - while (NULL != data) + while (NULL != data && data->committed) { if (NULL != largest_committed_csn && freeit) { csn_free(&largest_committed_csn); } - if (data->committed) { freeit = PR_TRUE; largest_committed_csn = data->csn; /* Save it */ if (first_commited && (*first_commited == NULL)) { @@ -294,9 +346,6 @@ csnplRollUp(CSNPL *csnpl, CSN **first_commited) data->csn = NULL; csnpldata_free(&data); data = (csnpldata *)llistRemoveCurrentAndGetNext(csnpl->csnList, &iterator); - } else { - data = (csnpldata *)llistGetNext (csnpl->csnList, &iterator); - } } #ifdef DEBUG @@ -326,6 +375,7 @@ static void _csnplDumpContentNoLock(CSNPL *csnpl, const char *caller) csnpldata *data; void *iterator; char csn_str[CSN_STRSIZE]; + char primcsn_str[CSN_STRSIZE]; data = (csnpldata *)llistGetFirst(csnpl->csnList, &iterator); if (data) { @@ -334,11 +384,18 @@ static void _csnplDumpContentNoLock(CSNPL *csnpl, const char *caller) } while (data) { - slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, "%s, %s\n", + slapi_log_err(SLAPI_LOG_REPL, repl_plugin_name, "%s,(prim %s), %s\n", csn_as_string(data->csn, PR_FALSE, csn_str), + data->prim_csn ? csn_as_string(data->prim_csn, PR_FALSE, primcsn_str) : " ", data->committed ? "committed" : "not committed"); data = (csnpldata *)llistGetNext (csnpl->csnList, &iterator); } } #endif +/* wrapper around csn_free, to satisfy NSPR thread context API */ +void +csnplFreeCSN (void *arg) +{ + csn_free((CSN **)&arg); +} diff --git a/ldap/servers/plugins/replication/csnpl.h b/ldap/servers/plugins/replication/csnpl.h index 3f6132d48..594c8f271 100644 --- a/ldap/servers/plugins/replication/csnpl.h +++ b/ldap/servers/plugins/replication/csnpl.h @@ -22,10 +22,13 @@ typedef struct csnpl CSNPL; CSNPL* csnplNew(void); void csnplFree (CSNPL **csnpl); -int csnplInsert (CSNPL *csnpl, const CSN *csn); +int csnplInsert (CSNPL *csnpl, const CSN *csn, const CSN *prim_csn); int csnplRemove (CSNPL *csnpl, const CSN *csn); +int csnplRemoveAll (CSNPL *csnpl, const CSN *csn); +int csnplCommitAll (CSNPL *csnpl, const CSN *csn); CSN* csnplGetMinCSN (CSNPL *csnpl, PRBool *committed); int csnplCommit (CSNPL *csnpl, const CSN *csn); CSN *csnplRollUp(CSNPL *csnpl, CSN ** first); void csnplDumpContent(CSNPL *csnpl, const char *caller); + #endif diff --git a/ldap/servers/plugins/replication/repl5.h b/ldap/servers/plugins/replication/repl5.h index 93342dd12..c3bd10cea 100644 --- a/ldap/servers/plugins/replication/repl5.h +++ b/ldap/servers/plugins/replication/repl5.h @@ -232,6 +232,8 @@ int multimaster_be_betxnpostop_modify (Slapi_PBlock *pb); extern int repl5_is_betxn; char* get_thread_private_agmtname(void); void set_thread_private_agmtname (const char *agmtname); +void set_thread_primary_csn (const CSN *prim_csn); +CSN* get_thread_primary_csn(void); void* get_thread_private_cache(void); void set_thread_private_cache (void *buf); char* get_repl_session_id (Slapi_PBlock *pb, char *id, CSN **opcsn); diff --git a/ldap/servers/plugins/replication/repl5_init.c b/ldap/servers/plugins/replication/repl5_init.c index a9aa5195f..0945f7b07 100644 --- a/ldap/servers/plugins/replication/repl5_init.c +++ b/ldap/servers/plugins/replication/repl5_init.c @@ -136,6 +136,7 @@ static int multimaster_started_flag = 0; /* Thread private data and interface */ static PRUintn thread_private_agmtname; /* thread private index for logging*/ static PRUintn thread_private_cache; +static PRUintn thread_primary_csn; char* get_thread_private_agmtname() @@ -153,6 +154,26 @@ set_thread_private_agmtname(const char *agmtname) PR_SetThreadPrivate(thread_private_agmtname, (void *)agmtname); } +CSN* +get_thread_primary_csn(void) +{ + CSN *prim_csn = NULL; + if (thread_primary_csn) + prim_csn = (CSN *)PR_GetThreadPrivate(thread_primary_csn); + return prim_csn; +} +void +set_thread_primary_csn(const CSN *prim_csn) +{ + if (thread_primary_csn) { + if (prim_csn) { + PR_SetThreadPrivate(thread_primary_csn, (void *)csn_dup(prim_csn)); + } else { + PR_SetThreadPrivate(thread_primary_csn, NULL); + } + } +} + void* get_thread_private_cache () { @@ -719,6 +740,7 @@ multimaster_start( Slapi_PBlock *pb ) /* Initialize thread private data for logging. Ignore if fails */ PR_NewThreadPrivateIndex (&thread_private_agmtname, NULL); PR_NewThreadPrivateIndex (&thread_private_cache, NULL); + PR_NewThreadPrivateIndex (&thread_primary_csn, csnplFreeCSN); /* Decode the command line args to see if we're dumping to LDIF */ is_ldif_dump = check_for_ldif_dump(pb); diff --git a/ldap/servers/plugins/replication/repl5_plugins.c b/ldap/servers/plugins/replication/repl5_plugins.c index 70e003bcb..357c093d9 100644 --- a/ldap/servers/plugins/replication/repl5_plugins.c +++ b/ldap/servers/plugins/replication/repl5_plugins.c @@ -1033,9 +1033,11 @@ static int write_changelog_and_ruv (Slapi_PBlock *pb) { Slapi_Operation *op = NULL; + CSN *opcsn; + CSN *prim_csn; int rc; slapi_operation_parameters *op_params = NULL; - Object *repl_obj; + Object *repl_obj = NULL; int return_value = SLAPI_PLUGIN_SUCCESS; Replica *r; Slapi_Backend *be; @@ -1063,17 +1065,17 @@ write_changelog_and_ruv (Slapi_PBlock *pb) { return return_value; } + /* we only log changes for operations applied to a replica */ + repl_obj = replica_get_replica_for_op (pb); + if (repl_obj == NULL) + return return_value; slapi_pblock_get(pb, SLAPI_RESULT_CODE, &rc); if (rc) { /* op failed - just return */ - return return_value; + cancel_opcsn(pb); + goto common_return; } - /* we only log changes for operations applied to a replica */ - repl_obj = replica_get_replica_for_op (pb); - if (repl_obj == NULL) - return return_value; - r = (Replica*)object_get_data (repl_obj); PR_ASSERT (r); @@ -1108,7 +1110,7 @@ write_changelog_and_ruv (Slapi_PBlock *pb) slapi_pblock_get (pb, SLAPI_OPERATION_PARAMETERS, &op_params); if (NULL == op_params) { - return return_value; + goto common_return; } /* need to set uniqueid operation parameter */ @@ -1127,19 +1129,18 @@ write_changelog_and_ruv (Slapi_PBlock *pb) slapi_pblock_get (pb, SLAPI_ENTRY_PRE_OP, &e); } if (NULL == e) { - return return_value; + goto common_return; } uniqueid = slapi_entry_get_uniqueid (e); if (NULL == uniqueid) { - return return_value; + goto common_return; } op_params->target_address.uniqueid = slapi_ch_strdup (uniqueid); } if( op_params->csn && is_cleaned_rid(csn_get_replicaid(op_params->csn))){ /* this RID has been cleaned */ - object_release (repl_obj); - return return_value; + goto common_return; } /* we might have stripped all the mods - in that case we do not @@ -1152,7 +1153,7 @@ write_changelog_and_ruv (Slapi_PBlock *pb) { slapi_log_err(SLAPI_LOG_CRIT, repl_plugin_name, "write_changelog_and_ruv - Skipped due to DISKFULL\n"); - return return_value; + goto common_return; } slapi_pblock_get(pb, SLAPI_TXN, &txn); rc = cl5WriteOperationTxn(repl_name, repl_gen, op_params, @@ -1188,7 +1189,6 @@ write_changelog_and_ruv (Slapi_PBlock *pb) */ if (0 == return_value) { char csn_str[CSN_STRSIZE] = {'\0'}; - CSN *opcsn; int rc; const char *dn = op_params ? REPL_GET_DN(&op_params->target_address) : "unknown"; Slapi_DN *sdn = op_params ? (&op_params->target_address)->sdn : NULL; @@ -1220,7 +1220,15 @@ write_changelog_and_ruv (Slapi_PBlock *pb) } } - object_release (repl_obj); +common_return: + opcsn = operation_get_csn(op); + prim_csn = get_thread_primary_csn(); + if (csn_is_equal(opcsn, prim_csn)) { + set_thread_primary_csn(NULL); + } + if (repl_obj) { + object_release (repl_obj); + } return return_value; } @@ -1417,7 +1425,7 @@ cancel_opcsn (Slapi_PBlock *pb) ruv_obj = replica_get_ruv (r); PR_ASSERT (ruv_obj); - ruv_cancel_csn_inprogress ((RUV*)object_get_data (ruv_obj), opcsn); + ruv_cancel_csn_inprogress ((RUV*)object_get_data (ruv_obj), opcsn, replica_get_rid(r)); object_release (ruv_obj); } diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index 04e7e8fae..7beef50ee 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -895,7 +895,7 @@ replica_update_ruv(Replica *r, const CSN *updated_csn, const char *replica_purl) } } /* Update max csn for local and remote replicas */ - rc = ruv_update_ruv (ruv, updated_csn, replica_purl, rid == r->repl_rid); + rc = ruv_update_ruv (ruv, updated_csn, replica_purl, r->repl_rid); if (RUV_COVERS_CSN == rc) { slapi_log_err(SLAPI_LOG_REPL, @@ -3618,7 +3618,7 @@ assign_csn_callback(const CSN *csn, void *data) if (NULL != r->min_csn_pl) { - if (csnplInsert(r->min_csn_pl, csn) != 0) + if (csnplInsert(r->min_csn_pl, csn, NULL) != 0) { char csn_str[CSN_STRSIZE]; /* For logging only */ /* Ack, we can't keep track of min csn. Punt. */ @@ -3666,7 +3666,7 @@ abort_csn_callback(const CSN *csn, void *data) } } - ruv_cancel_csn_inprogress (ruv, csn); + ruv_cancel_csn_inprogress (ruv, csn, replica_get_rid(r)); replica_unlock(r->repl_lock); object_release (ruv_obj); diff --git a/ldap/servers/plugins/replication/repl5_ruv.c b/ldap/servers/plugins/replication/repl5_ruv.c index c2a9d19b2..111b88f4b 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.c +++ b/ldap/servers/plugins/replication/repl5_ruv.c @@ -77,6 +77,7 @@ static char *get_replgen_from_berval(const struct berval *bval); static const char * const prefix_replicageneration = "{replicageneration}"; static const char * const prefix_ruvcsn = "{replica "; /* intentionally missing '}' */ +static int ruv_update_ruv_element (RUV *ruv, RUVElement *replica, const CSN *csn, const char *replica_purl, PRBool isLocal); /* API implementation */ @@ -1604,6 +1605,7 @@ int ruv_add_csn_inprogress (RUV *ruv, const CSN *csn) char csn_str[CSN_STRSIZE]; int rc = RUV_SUCCESS; int rid = csn_get_replicaid (csn); + CSN *prim_csn; PR_ASSERT (ruv && csn); @@ -1641,8 +1643,12 @@ int ruv_add_csn_inprogress (RUV *ruv, const CSN *csn) rc = RUV_COVERS_CSN; goto done; } - - rc = csnplInsert (replica->csnpl, csn); + prim_csn = get_thread_primary_csn(); + if (prim_csn == NULL) { + set_thread_primary_csn(csn); + prim_csn = get_thread_primary_csn(); + } + rc = csnplInsert (replica->csnpl, csn, prim_csn); if (rc == 1) /* we already seen this csn */ { if (slapi_is_loglevel_set(SLAPI_LOG_REPL)) { @@ -1650,6 +1656,7 @@ int ruv_add_csn_inprogress (RUV *ruv, const CSN *csn) "The csn %s has already be seen - ignoring\n", csn_as_string (csn, PR_FALSE, csn_str)); } + set_thread_primary_csn(NULL); rc = RUV_COVERS_CSN; } else if(rc != 0) @@ -1674,24 +1681,36 @@ done: return rc; } -int ruv_cancel_csn_inprogress (RUV *ruv, const CSN *csn) +int ruv_cancel_csn_inprogress (RUV *ruv, const CSN *csn, ReplicaId local_rid) { RUVElement* replica; int rc = RUV_SUCCESS; + CSN *prim_csn = NULL; + PR_ASSERT (ruv && csn); + prim_csn = get_thread_primary_csn(); /* locate ruvElement */ slapi_rwlock_wrlock (ruv->lock); replica = ruvGetReplica (ruv, csn_get_replicaid (csn)); - if (replica == NULL) - { + if (replica == NULL) { /* ONREPL - log error */ - rc = RUV_NOTFOUND; - goto done; - } - - rc = csnplRemove (replica->csnpl, csn); + rc = RUV_NOTFOUND; + goto done; + } + if (csn_is_equal(csn, prim_csn)) { + /* the prim csn is cancelled, lets remove all dependent csns */ + ReplicaId prim_rid = csn_get_replicaid (csn); + replica = ruvGetReplica (ruv, prim_rid); + rc = csnplRemoveAll (replica->csnpl, prim_csn); + if (prim_rid != local_rid) { + replica = ruvGetReplica (ruv, local_rid); + rc = csnplRemoveAll (replica->csnpl, prim_csn); + } + } else { + rc = csnplRemove (replica->csnpl, csn); + } if (rc != 0) rc = RUV_NOTFOUND; else @@ -1702,19 +1721,37 @@ done: return rc; } -int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, PRBool isLocal) +int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, ReplicaId local_rid) +{ + int rc=RUV_SUCCESS; + RUVElement *replica; + ReplicaId prim_rid; + + CSN *prim_csn = get_thread_primary_csn(); + + if (! csn_is_equal(csn, prim_csn)) { + /* not a primary csn, nothing to do */ + return rc; + } + slapi_rwlock_wrlock (ruv->lock); + prim_rid = csn_get_replicaid (csn); + replica = ruvGetReplica (ruv, local_rid); + rc = ruv_update_ruv_element(ruv, replica, csn, replica_purl, PR_TRUE); + if ( rc || local_rid == prim_rid) goto done; + replica = ruvGetReplica (ruv, prim_rid); + rc = ruv_update_ruv_element(ruv, replica, csn, replica_purl, PR_FALSE); +done: + slapi_rwlock_unlock (ruv->lock); + return rc; +} +static int +ruv_update_ruv_element (RUV *ruv, RUVElement *replica, const CSN *csn, const char *replica_purl, PRBool isLocal) { int rc=RUV_SUCCESS; char csn_str[CSN_STRSIZE]; CSN *max_csn; CSN *first_csn = NULL; - RUVElement *replica; - PR_ASSERT (ruv && csn); - - slapi_rwlock_wrlock (ruv->lock); - - replica = ruvGetReplica (ruv, csn_get_replicaid (csn)); if (replica == NULL) { /* we should have a ruv element at this point because it would have @@ -1724,7 +1761,7 @@ int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, PRBool i goto done; } - if (csnplCommit(replica->csnpl, csn) != 0) + if (csnplCommitAll(replica->csnpl, csn) != 0) { slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "ruv_update_ruv - Cannot commit csn %s\n", csn_as_string(csn, PR_FALSE, csn_str)); @@ -1765,7 +1802,6 @@ int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, PRBool i } done: - slapi_rwlock_unlock (ruv->lock); return rc; } diff --git a/ldap/servers/plugins/replication/repl5_ruv.h b/ldap/servers/plugins/replication/repl5_ruv.h index e9eff5aac..c8960fd3a 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.h +++ b/ldap/servers/plugins/replication/repl5_ruv.h @@ -109,8 +109,8 @@ PRInt32 ruv_replica_count (const RUV *ruv); char **ruv_get_referrals(const RUV *ruv); void ruv_dump(const RUV *ruv, char *ruv_name, PRFileDesc *prFile); int ruv_add_csn_inprogress (RUV *ruv, const CSN *csn); -int ruv_cancel_csn_inprogress (RUV *ruv, const CSN *csn); -int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, PRBool isLocal); +int ruv_cancel_csn_inprogress (RUV *ruv, const CSN *csn, ReplicaId rid); +int ruv_update_ruv (RUV *ruv, const CSN *csn, const char *replica_purl, ReplicaId local_rid); int ruv_move_local_supplier_to_first(RUV *ruv, ReplicaId rid); int ruv_get_first_id_and_purl(RUV *ruv, ReplicaId *rid, char **replica_purl ); int ruv_local_contains_supplier(RUV *ruv, ReplicaId rid); diff --git a/ldap/servers/slapd/csn.c b/ldap/servers/slapd/csn.c index ce14816c5..5b420bf68 100644 --- a/ldap/servers/slapd/csn.c +++ b/ldap/servers/slapd/csn.c @@ -268,6 +268,21 @@ csn_as_attr_option_string(CSNType t,const CSN *csn,char *ss) return s; } +int +csn_is_equal(const CSN *csn1, const CSN *csn2) +{ + int retval = 0; + if ((csn1 == NULL && csn2 == NULL) || + (csn1 && csn2 && + csn1->tstamp == csn2->tstamp && + csn1->seqnum == csn2->seqnum && + csn1->rid == csn2->rid && + csn1->subseqnum == csn2->subseqnum)) { + retval = 1; + } + return retval; +} + int csn_compare_ext(const CSN *csn1, const CSN *csn2, unsigned int flags) { diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 406b014e5..dd180a75a 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -174,6 +174,7 @@ time_t csn_get_time(const CSN *csn); PRUint16 csn_get_seqnum(const CSN *csn); PRUint16 csn_get_subseqnum(const CSN *csn); char *csn_as_string(const CSN *csn, PRBool replicaIdOrder, char *ss); /* WARNING: ss must be CSN_STRSIZE bytes, or NULL. */ +int csn_is_equal(const CSN *csn1, const CSN *csn2); int csn_compare(const CSN *csn1, const CSN *csn2); int csn_compare_ext(const CSN *csn1, const CSN *csn2, unsigned int flags); #define CSN_COMPARE_SKIP_SUBSEQ 0x1 @@ -189,6 +190,7 @@ const CSN *csn_max(const CSN *csn1,const CSN *csn2); a csn from the set.*/ int csn_increment_subsequence (CSN *csn); +void csnplFreeCSN (void *arg); /* * csnset.c */
0
61953fc2d47f134795f365e60b1286dd8b0cd1de
389ds/389-ds-base
fix for reg in 49008, check if ruv element exists
commit 61953fc2d47f134795f365e60b1286dd8b0cd1de Author: Ludwig Krispenz <[email protected]> Date: Tue Feb 7 17:02:00 2017 +0100 fix for reg in 49008, check if ruv element exists diff --git a/ldap/servers/plugins/replication/repl5_ruv.c b/ldap/servers/plugins/replication/repl5_ruv.c index 111b88f4b..d59e6d227 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.c +++ b/ldap/servers/plugins/replication/repl5_ruv.c @@ -1705,8 +1705,14 @@ int ruv_cancel_csn_inprogress (RUV *ruv, const CSN *csn, ReplicaId local_rid) replica = ruvGetReplica (ruv, prim_rid); rc = csnplRemoveAll (replica->csnpl, prim_csn); if (prim_rid != local_rid) { - replica = ruvGetReplica (ruv, local_rid); - rc = csnplRemoveAll (replica->csnpl, prim_csn); + if( local_rid != READ_ONLY_REPLICA_ID) { + replica = ruvGetReplica (ruv, local_rid); + if (replica) { + rc = csnplRemoveAll (replica->csnpl, prim_csn); + } else { + rc = RUV_NOTFOUND; + } + } } } else { rc = csnplRemove (replica->csnpl, csn);
0
c77825521aa7e4aea0776c73ee7f0792466c7514
389ds/389-ds-base
Issue 50488 - Create a monitor for disk space usagedisk-space-mon Description: Create a new monitor object: cn=disk space,cn=monitor. It contains 'dsDisk' multi-valued attribute which has a format: dsdisk: partition="/" size="42006183936" used="35768864768" available="6237319 168" use%="85" dsdisk: partition="/tmp" size="1023303680" used="950198272" available="7310540 8" use%="92" Add MonitorDiskSpace(DSLdapObject) to monitor.py. Add a test to check the basic functionality. Remove unused code and its statfs.h dependency. Remove SLAPD_MONITOR_DN definition because it is unused. https://pagure.io/389-ds-base/issue/50488 Authors: spichugi, mreynolds Reviewed by: mreynolds, tbordaz, mhonek (Thanks!)
commit c77825521aa7e4aea0776c73ee7f0792466c7514 Author: Simon Pichugin <[email protected]> Date: Wed Jul 24 11:04:11 2019 +0200 Issue 50488 - Create a monitor for disk space usagedisk-space-mon Description: Create a new monitor object: cn=disk space,cn=monitor. It contains 'dsDisk' multi-valued attribute which has a format: dsdisk: partition="/" size="42006183936" used="35768864768" available="6237319 168" use%="85" dsdisk: partition="/tmp" size="1023303680" used="950198272" available="7310540 8" use%="92" Add MonitorDiskSpace(DSLdapObject) to monitor.py. Add a test to check the basic functionality. Remove unused code and its statfs.h dependency. Remove SLAPD_MONITOR_DN definition because it is unused. https://pagure.io/389-ds-base/issue/50488 Authors: spichugi, mreynolds Reviewed by: mreynolds, tbordaz, mhonek (Thanks!) diff --git a/dirsrvtests/tests/suites/disk_monitoring/disk_space_test.py b/dirsrvtests/tests/suites/disk_monitoring/disk_space_test.py new file mode 100644 index 000000000..892c78eb6 --- /dev/null +++ b/dirsrvtests/tests/suites/disk_monitoring/disk_space_test.py @@ -0,0 +1,45 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +from lib389.monitor import MonitorDiskSpace +from lib389.topologies import topology_st as topo + + +def test_basic(topo): + """Test that the cn=disk space,cn=monitor gives at least one value + + :id: f1962762-2c6c-4e50-97af-a00012a7486d + :setup: Standalone + :steps: + 1. Get cn=disk space,cn=monitor entry + 2. Check it has at least one dsDisk attribute + 3. Check dsDisk attribute has the partition and sizes + 4. Check the numbers are valid integers + :expectedresults: + 1. It should succeed + 2. It should succeed + 3. It should succeed + 4. It should succeed + """ + + inst = topo.standalone + + # Turn off disk monitoring + disk_space_mon = MonitorDiskSpace(inst) + disk_str = disk_space_mon.get_disks()[0] + + inst.log.info('Check that "partition", "size", "used", "available", "use%" words are present in the string') + words = ["partition", "size", "used", "available", "use%"] + assert all(map(lambda word: word in disk_str, words)) + + inst.log.info("Check that the sizes are numbers") + for word in words[1:]: + number = disk_str.split(f'{word}="')[1].split('"')[0] + try: + int(number) + except ValueError: + raise ValueError(f'A "{word}" value is not a number') diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index a240d6e78..9aed66323 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -42,14 +42,13 @@ #if defined(LINUX) || defined(__FreeBSD__) #ifdef LINUX #undef CTIME -#include <sys/statfs.h> #endif /* linux*/ #include <sys/param.h> #include <sys/mount.h> #else /* Linux or fbsd */ -#include <sys/statvfs.h> #include <sys/mnttab.h> #endif +#include <sys/statvfs.h> #include "slap.h" #include "slapi-plugin.h" #include "snmp_collator.h" @@ -210,67 +209,8 @@ static int time_shutdown = 0; /* * Return a copy of the mount point for the specified directory */ -#ifdef SOLARIS -char * -disk_mon_get_mount_point(char *dir) -{ - struct mnttab mnt; - struct stat s; - dev_t dev_id; - FILE *fp; - - fp = fopen("/etc/mnttab", "r"); - - if (fp == NULL || stat(dir, &s) != 0) { - return NULL; - } - - dev_id = s.st_dev; - - while ((0 == getmntent(fp, &mnt))) { - if (stat(mnt.mnt_mountp, &s) != 0) { - continue; - } - if (s.st_dev == dev_id) { - return (slapi_ch_strdup(mnt.mnt_mountp)); - } - } - - return NULL; -} -#elif HPUX -char * -disk_mon_get_mount_point(char *dir) -{ - struct mntent *mnt; - struct stat s; - dev_t dev_id; - FILE *fp; - - if ((fp = setmntent("/etc/mnttab", "r")) == NULL) { - return NULL; - } - - if (stat(dir, &s) != 0) { - return NULL; - } - - dev_id = s.st_dev; - - while ((mnt = getmntent(fp))) { - if (stat(mnt->mnt_dir, &s) != 0) { - continue; - } - if (s.st_dev == dev_id) { - endmntent(fp); - return (slapi_ch_strdup(mnt->mnt_dir)); - } - } - endmntent(fp); - return NULL; -} -#elif LINUX /* Linux */ +#if LINUX char * disk_mon_get_mount_point(char *dir) { @@ -304,8 +244,8 @@ disk_mon_get_mount_point(char *dir) char * disk_mon_get_mount_point(char *dir) { - struct statfs sb; - if (statfs(dir, &sb) != 0) { + struct statvfs sb; + if (statvfs(dir, &sb) != 0) { return NULL; } @@ -337,14 +277,14 @@ disk_mon_add_dir(char ***list, char *directory) * We gather all the log, txn log, config, and db directories */ void -disk_mon_get_dirs(char ***list, int logs_critical __attribute__((unused))) +disk_mon_get_dirs(char ***list) { slapdFrontendConfig_t *config = getFrontendConfig(); Slapi_Backend *be = NULL; char *cookie = NULL; char *dir = NULL; -/* Add /var just to be safe */ + /* Add /var just to be safe */ #ifdef LOCALSTATEDIR disk_mon_add_dir(list, LOCALSTATEDIR); #else @@ -362,10 +302,12 @@ disk_mon_get_dirs(char ***list, int logs_critical __attribute__((unused))) be = slapi_get_first_backend(&cookie); while (be) { - if (slapi_back_get_info(be, BACK_INFO_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) { /* db directory */ + if (slapi_back_get_info(be, BACK_INFO_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) { + /* db directory */ disk_mon_add_dir(list, dir); } - if (slapi_back_get_info(be, BACK_INFO_LOG_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) { /* txn log dir */ + if (slapi_back_get_info(be, BACK_INFO_LOG_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) { + /* txn log dir */ disk_mon_add_dir(list, dir); } be = (backend *)slapi_get_next_backend(cookie); @@ -373,33 +315,53 @@ disk_mon_get_dirs(char ***list, int logs_critical __attribute__((unused))) slapi_ch_free((void **)&cookie); } +/* + * This function gets the stats of the directory and returns total space, + * available space, and used space of the directory. + */ +int32_t +disk_get_info(char *dir, uint64_t *total_space, uint64_t *avail_space, uint64_t *used_space) +{ + int32_t rc = LDAP_SUCCESS; + struct statvfs buf; + uint64_t freeBytes = 0; + uint64_t blockSize = 0; + uint64_t blocks = 0; + + if (statvfs(dir, &buf) != -1) { + LL_UI2L(freeBytes, buf.f_bavail); + LL_UI2L(blockSize, buf.f_bsize); + LL_UI2L(blocks, buf.f_blocks); + LL_MUL(*total_space, blocks, blockSize); + LL_MUL(*avail_space, freeBytes, blockSize); + *used_space = *total_space - *avail_space; + } else { + *total_space = 0; + *avail_space = 0; + *used_space = 0; + rc = -1; + } + return rc; +} + /* * This function checks the list of directories to see if any are below the - * threshold. We return the the directory/free disk space of the most critical + * threshold. We return the directory/free disk space of the most critical * directory. */ char * -disk_mon_check_diskspace(char **dirs, PRUint64 threshold, PRUint64 *disk_space) +disk_mon_check_diskspace(char **dirs, uint64_t threshold, uint64_t *disk_space) { -#if defined(LINUX) || defined(__FreeBSD__) - struct statfs buf; -#else struct statvfs buf; -#endif - PRUint64 worst_disk_space = threshold; - PRUint64 freeBytes = 0; - PRUint64 blockSize = 0; + uint64_t worst_disk_space = threshold; + uint64_t freeBytes = 0; + uint64_t blockSize = 0; char *worst_dir = NULL; int hit_threshold = 0; int i = 0; for (i = 0; dirs && dirs[i]; i++) { -#if defined(LINUX) || defined(__FreeBSD__) - if (statfs(dirs[i], &buf) != -1) -#else - if (statvfs(dirs[i], &buf) != -1) -#endif - { + if (statvfs(dirs[i], &buf) != -1) { LL_UI2L(freeBytes, buf.f_bavail); LL_UI2L(blockSize, buf.f_bsize); LL_MUL(freeBytes, freeBytes, blockSize); @@ -444,10 +406,10 @@ disk_monitoring_thread(void *nothing __attribute__((unused))) { char **dirs = NULL; char *dirstr = NULL; - PRUint64 previous_mark = 0; - PRUint64 disk_space = 0; - PRInt64 threshold = 0; - PRUint64 halfway = 0; + uint64_t previous_mark = 0; + uint64_t disk_space = 0; + int64_t threshold = 0; + uint64_t halfway = 0; time_t start = 0; time_t now = 0; int deleted_rotated_logs = 0; @@ -500,7 +462,7 @@ disk_monitoring_thread(void *nothing __attribute__((unused))) */ slapi_ch_array_free(dirs); dirs = NULL; - disk_mon_get_dirs(&dirs, logging_critical); + disk_mon_get_dirs(&dirs); dirstr = disk_mon_check_diskspace(dirs, threshold, &disk_space); if (dirstr == NULL) { /* @@ -1630,7 +1592,7 @@ ns_handle_closure(struct ns_job_t *job) /** * Schedule more I/O for this connection, or make sure that it * is closed in the event loop. - * + * * caller must hold c_mutex */ void diff --git a/ldap/servers/slapd/fedse.c b/ldap/servers/slapd/fedse.c index 001750afd..3e498949c 100644 --- a/ldap/servers/slapd/fedse.c +++ b/ldap/servers/slapd/fedse.c @@ -88,6 +88,11 @@ static const char *internal_entries[] = "cn:monitor\n" "aci: (target =\"ldap:///cn=monitor*\")(targetattr != \"aci || connection\")(version 3.0; acl \"monitor\"; allow( read, search, compare ) userdn = \"ldap:///anyone\";)\n", + "dn:cn=disk space,cn=monitor\n" + "objectclass:top\n" + "objectclass:extensibleObject\n" + "cn:disk space\n", + "dn:cn=snmp,cn=monitor\n" "objectclass:top\n" "objectclass:extensibleObject\n" @@ -2805,10 +2810,12 @@ setup_internal_backends(char *configdir) Slapi_DN encryption; Slapi_DN saslmapping; Slapi_DN plugins; + Slapi_DN diskspace; slapi_sdn_init_ndn_byref(&monitor, "cn=monitor"); slapi_sdn_init_ndn_byref(&counters, "cn=counters,cn=monitor"); slapi_sdn_init_ndn_byref(&snmp, "cn=snmp,cn=monitor"); + slapi_sdn_init_ndn_byref(&diskspace, "cn=disk space,cn=monitor"); slapi_sdn_init_ndn_byref(&root, ""); slapi_sdn_init_ndn_byref(&encryption, "cn=encryption,cn=config"); @@ -2818,6 +2825,7 @@ setup_internal_backends(char *configdir) /* Search */ dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &config, LDAP_SCOPE_BASE, "(objectclass=*)", read_config_dse, NULL, NULL); dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &monitor, LDAP_SCOPE_BASE, "(objectclass=*)", monitor_info, NULL, NULL); + dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &diskspace, LDAP_SCOPE_BASE, "(objectclass=*)", monitor_disk_info, NULL, NULL); dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &root, LDAP_SCOPE_BASE, "(objectclass=*)", read_root_dse, NULL, NULL); dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &monitor, LDAP_SCOPE_SUBTREE, EGG_FILTER, search_easter_egg, NULL, NULL); /* Egg */ dse_register_callback(pfedse, SLAPI_OPERATION_SEARCH, DSE_FLAG_PREOP, &counters, LDAP_SCOPE_BASE, "(objectclass=*)", search_counters, NULL, NULL); diff --git a/ldap/servers/slapd/monitor.c b/ldap/servers/slapd/monitor.c index 68c4864c1..562721bed 100644 --- a/ldap/servers/slapd/monitor.c +++ b/ldap/servers/slapd/monitor.c @@ -1,6 +1,6 @@ /** BEGIN COPYRIGHT BLOCK * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. + * Copyright (C) 2019 Red Hat, Inc. * All rights reserved. * * License: GPL (version 3 or any later version). @@ -31,10 +31,7 @@ #include "slap.h" #include "fe.h" -#if defined(SLAPD_MONITOR_DN) - - -int +int32_t monitor_info(Slapi_PBlock *pb __attribute__((unused)), Slapi_Entry *e, Slapi_Entry *entryAfter __attribute__((unused)), @@ -97,14 +94,10 @@ monitor_info(Slapi_PBlock *pb __attribute__((unused)), val.bv_val = buf; attrlist_replace(&e->e_attrs, "nbackends", vals); -#ifdef THREAD_SUNOS5_LWP - val.bv_len = snprintf(buf, sizeof(buf), "%d", thr_getconcurrency()); - val.bv_val = buf; - attrlist_replace(&e->e_attrs, "concurrency", vals); -#endif - - /*Loop through the backends, and stuff the monitordns - into the entry we're sending back*/ + /* + * Loop through the backends, and stuff the monitor dn's + * into the entry we're sending back + */ attrlist_delete(&e->e_attrs, "backendmonitordn"); cookie = NULL; be = slapi_get_first_backend(&cookie); @@ -127,8 +120,47 @@ monitor_info(Slapi_PBlock *pb __attribute__((unused)), return SLAPI_DSE_CALLBACK_OK; } -#endif /* SLAPD_MONITOR_DN */ +int32_t +monitor_disk_info (Slapi_PBlock *pb __attribute__((unused)), + Slapi_Entry *e, + Slapi_Entry *entryAfter __attribute__((unused)), + int *returncode, + char *returntext __attribute__((unused)), + void *arg __attribute__((unused))) +{ + int32_t rc = LDAP_SUCCESS; + char **dirs = NULL; + char buf[BUFSIZ]; + struct berval val; + struct berval *vals[2]; + uint64_t total_space; + uint64_t avail_space; + uint64_t used_space; + + vals[0] = &val; + vals[1] = NULL; + + disk_mon_get_dirs(&dirs); + + for (uint16_t i = 0; dirs && dirs[i]; i++) { + rc = disk_get_info(dirs[i], &total_space, &avail_space, &used_space); + if (rc) { + slapi_log_err(SLAPI_LOG_WARNING, "monitor_disk_info", + "Unable to get 'cn=disk space,cn=monitor' stats for %s\n", dirs[i]); + } else { + val.bv_len = snprintf(buf, sizeof(buf), + "partition=\"%s\" size=\"%" PRIu64 "\" used=\"%" PRIu64 "\" available=\"%" PRIu64 "\" use%%=\"%" PRIu64 "\"", + dirs[i], total_space, used_space, avail_space, used_space * 100 / total_space); + val.bv_val = buf; + attrlist_merge(&e->e_attrs, "dsDisk", vals); + } + } + slapi_ch_array_free(dirs); + + *returncode = rc; + return SLAPI_DSE_CALLBACK_OK; +} /* * Return a malloc'd version value. @@ -142,11 +174,9 @@ slapd_get_version_value(void) versionstring = config_get_versionstring(); buildnum = config_get_buildnum(); - vs = slapi_ch_smprintf("%s B%s", versionstring, buildnum); - - slapi_ch_free((void **)&buildnum); - slapi_ch_free((void **)&versionstring); + slapi_ch_free_string(&buildnum); + slapi_ch_free_string(&versionstring); return vs; } diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 2fa413609..b7e82c833 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -873,7 +873,8 @@ void freepmods(LDAPMod **pmods); /* * monitor.c */ -int monitor_info(Slapi_PBlock *pb, Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, int *returncode, char *returntext, void *arg); +int32_t monitor_info(Slapi_PBlock *pb, Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, int *returncode, char *returntext, void *arg); +int32_t monitor_disk_info(Slapi_PBlock *pb, Slapi_Entry *entryBefore, Slapi_Entry *entryAfter, int *returncode, char *returntext, void *arg); char *slapd_get_version_value(void); @@ -1485,6 +1486,8 @@ void handle_closed_connection(Connection *); void slapd_do_nothing(int); #endif void slapd_wait4child(int); +void disk_mon_get_dirs(char ***list); +int32_t disk_get_info(char *dir, uint64_t *total_space, uint64_t *avail_space, uint64_t *used_space); void ns_handle_pr_read_ready(struct ns_job_t *job); void ns_connection_post_io_or_closing(Connection *conn); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 0c8d66276..7a68e60ab 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -301,7 +301,6 @@ typedef void (*VFPV)(); /* takes undefined arguments */ #define SLAPD_DEFAULT_LDAPI_SEARCH_BASE "dc=example,dc=com" #define SLAPD_DEFAULT_LDAPI_AUTO_DN "cn=peercred,cn=external,cn=auth" -#define SLAPD_MONITOR_DN "cn=monitor" #define SLAPD_SCHEMA_DN "cn=schema" #define SLAPD_CONFIG_DN "cn=config" diff --git a/src/lib389/lib389/monitor.py b/src/lib389/lib389/monitor.py index 9ee16b2c1..5ca967c64 100644 --- a/src/lib389/lib389/monitor.py +++ b/src/lib389/lib389/monitor.py @@ -246,3 +246,16 @@ class MonitorSNMP(DSLdapObject): def get_status(self, use_json=False): return self.get_attrs_vals_utf8(self._snmp_keys) + + +class MonitorDiskSpace(DSLdapObject): + """A class for representing "cn=disk space,cn=monitor" entry""" + + def __init__(self, instance, dn=None): + super(MonitorDiskSpace, self).__init__(instance=instance, dn=dn) + self._dn = "cn=disk space,cn=monitor" + + def get_disks(self): + """Get an information about partitions which contains a Directory Server data""" + + return self.get_attr_vals_utf8_l("dsDisk")
0
5e4551e9d6ddbfae49221eb10b12914c872d31b6
389ds/389-ds-base
Issue 4812 - Listener thread does not scale with a high num of established connections (#5706) Bug description: Latest commit introduced zero alloc bug. Fix description: A memory allocation is attempted before the required size is known. Introduced during rework. relates: https://github.com/389ds/389-ds-base/issues/4812 Reviewed by: @mreynolds389 (Thank you)
commit 5e4551e9d6ddbfae49221eb10b12914c872d31b6 Author: James Chapman <[email protected]> Date: Mon Mar 20 23:19:08 2023 +0000 Issue 4812 - Listener thread does not scale with a high num of established connections (#5706) Bug description: Latest commit introduced zero alloc bug. Fix description: A memory allocation is attempted before the required size is known. Introduced during rework. relates: https://github.com/389ds/389-ds-base/issues/4812 Reviewed by: @mreynolds389 (Thank you) diff --git a/ldap/servers/slapd/conntable.c b/ldap/servers/slapd/conntable.c index 2cf7f4020..6b8052591 100644 --- a/ldap/servers/slapd/conntable.c +++ b/ldap/servers/slapd/conntable.c @@ -129,8 +129,8 @@ connection_table_new(int table_size) int free_idx = 0; ber_len_t maxbersize = config_get_maxbersize(); ct = (Connection_Table *)slapi_ch_calloc(1, sizeof(Connection_Table)); - ct->num_active = (int *)slapi_ch_calloc(1, ct->list_num * sizeof(int)); ct->list_num = config_get_num_listeners(); + ct->num_active = (int *)slapi_ch_calloc(1, ct->list_num * sizeof(int)); ct->size = table_size - (table_size % ct->list_num); ct->list_size = ct->size/ct->list_num; ct->num_active = (int *)slapi_ch_calloc(1, ct->list_num * sizeof(int));
0
3111a1660b490703863f7dd0f2a9f5cab2851cc8
389ds/389-ds-base
Issue 2820 - Fix CI test suite issues Bug Description: Test collection fails due to file name clash - basic_test.py is present in other suites too. Fix Description: Add a missing a __init__.py file. Relates: https://github.com/389ds/389-ds-base/issues/2820 Reviewed by: @droideck (Thanks!)
commit 3111a1660b490703863f7dd0f2a9f5cab2851cc8 Author: Viktor Ashirov <[email protected]> Date: Wed May 26 10:55:29 2021 +0200 Issue 2820 - Fix CI test suite issues Bug Description: Test collection fails due to file name clash - basic_test.py is present in other suites too. Fix Description: Add a missing a __init__.py file. Relates: https://github.com/389ds/389-ds-base/issues/2820 Reviewed by: @droideck (Thanks!) diff --git a/dirsrvtests/tests/suites/retrocl/__init__.py b/dirsrvtests/tests/suites/retrocl/__init__.py new file mode 100644 index 000000000..404a59b09 --- /dev/null +++ b/dirsrvtests/tests/suites/retrocl/__init__.py @@ -0,0 +1,3 @@ +""" + :Requirement: 389-ds-base: Retro Changelog plugin +"""
0
b032f7194cdc7ba4ba7e534925d7e13c43ca6594
389ds/389-ds-base
Ticket 48050 - Refactor acctpolicy_plugin suite Description: Add 3 test cases, fix docstrings and add pytest.raises. https://fedorahosted.org/389/ticket/48050 Reviewed by: spichugi Signed-off-by: Simon Pichugin <[email protected]>
commit b032f7194cdc7ba4ba7e534925d7e13c43ca6594 Author: Sankar Ramalingam <[email protected]> Date: Wed Jan 4 17:59:20 2017 +0530 Ticket 48050 - Refactor acctpolicy_plugin suite Description: Add 3 test cases, fix docstrings and add pytest.raises. https://fedorahosted.org/389/ticket/48050 Reviewed by: spichugi Signed-off-by: Simon Pichugin <[email protected]> diff --git a/dirsrvtests/tests/suites/acctpolicy_plugin/accpol_test.py b/dirsrvtests/tests/suites/acctpolicy_plugin/accpol_test.py index a005f3f49..3cf93b051 100644 --- a/dirsrvtests/tests/suites/acctpolicy_plugin/accpol_test.py +++ b/dirsrvtests/tests/suites/acctpolicy_plugin/accpol_test.py @@ -20,21 +20,13 @@ TEMPLT_COS = 'cn=TempltCoS,ou=people,dc=example,dc=com' DEFN_COS = 'cn=DefnCoS,ou=people,dc=example,dc=com' ACCPOL_DN = "cn={},{}".format(PLUGIN_ACCT_POLICY, DN_PLUGIN) CONFIG_DN = "cn=config,{}".format(ACCPOL_DN) -SUBTREE = 'ou=people' -SUFFIX = DEFAULT_SUFFIX -USR_NAME = 'testusr' -NOF_USERS = 5 INACT_VAL = 15 -USR_RDN = '{}'.format(USR_NAME) -USR_DN = 'uid={},{},{}'.format(USR_RDN, SUBTREE, SUFFIX) USER_PW = 'Secret1234' @pytest.fixture(scope="module") def accpolicy_local(topology_st): - """Configure account policy plugin based - on LDIF file and restart the server. - """ + """Configure local account policy plugin for ou=people subtree and restart the server""" log.info('Enabling account policy plugin and restarting the server') try: @@ -46,10 +38,10 @@ def accpolicy_local(topology_st): topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'specattrname', 'acctPolicySubentry')]) topology_st.standalone.modify_s(CONFIG_DN, [(ldap.MOD_REPLACE, 'limitattrname', 'accountInactivityLimit')]) except ldap.LDAPError as e: - log.error("Failed to modify account policy plugin attrs attrs") + log.error('Failed to modify account policy plugin attrs') raise - log.info("Adding Local account policy plugin configuration entries") + log.info('Adding Local account policy plugin configuration entries') try: topology_st.standalone.add_s(Entry((LOCAL_CONFIG, { 'objectclass': ['top', 'ldapsubentry', 'extensibleObject', 'accountpolicy'], @@ -67,92 +59,183 @@ def accpolicy_local(topology_st): topology_st.standalone.restart(timeout=10) [email protected](scope="module") -def users(topology_st, request): - """Add users to the given SUFFIX and SUBTREE.""" +def add_users(topology_st, suffix, subtre, userid, nousrs): + """Add users to default test instance with given suffix, subtre, userid and nousrs""" - log.info('Adding {} {} users to {} SUBTREE {} SUFFIX'.format(NOF_USERS, USR_NAME, SUBTREE, SUFFIX)) - for NUM in range(1, NOF_USERS): - USR_RDN = '{}{}'.format(USR_NAME, NUM) - USR_DN = 'uid={},{},{}'.format(USR_RDN, SUBTREE, SUFFIX) + log.info('add_users: Pass all of these as parameteres suffix, subtre, userid and nousrs') + topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) + while (nousrs > 0): + usrrdn = '{}{}'.format(userid, nousrs) + userdn = 'uid={},{},{}'.format(usrrdn, subtre, suffix) try: - topology_st.standalone.add_s(Entry((USR_DN, { + topology_st.standalone.add_s(Entry((userdn, { 'objectclass': 'top person'.split(), 'objectclass': 'inetorgperson', - 'cn': USR_RDN, - 'sn': USR_RDN, - 'userpassword': 'Secret1234', - 'mail': '{}@redhat.com'.format(USR_RDN)}))) + 'cn': usrrdn, + 'sn': usrrdn, + 'userpassword': USER_PW, + 'mail': '{}@redhat.com'.format(usrrdn)}))) except ldap.LDAPError as e: - log.error('Failed to add {} user: error {}'.format(USR_DN, e.message['desc'])) + log.error('Failed to add {} user: error {}'.format(userdn, e.message['desc'])) raise + nousrs = nousrs - 1 - def fin(): - log.info('Deleting {} {} users from {} {}'.format(NOF_USERS, USR_NAME, SUBTREE, SUFFIX)) - topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) - for NUM in range(1, NOF_USERS): - USR_RDN = '{}{}'.format(USR_NAME, NUM) - USR_DN = 'uid={},{},{}'.format(USR_RDN, SUBTREE, SUFFIX) + +def del_users(topology_st, suffix, subtre, userid, nousrs): + """Delete users from default test instance with given suffix, subtre, userid and nousrs""" + + log.info('del_users: Pass all of these as parameteres suffix, subtre, userid and nousrs') + topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) + while (nousrs > 0): + usrrdn = '{}{}'.format(userid, nousrs) + userdn = 'uid={},{},{}'.format(usrrdn, subtre, suffix) + try: + topology_st.standalone.delete_s(userdn) + except ldap.LDAPError as e: + log.error('Failed to delete {} user: error {}'.format(userdn, e.message['desc'])) + raise + nousrs = nousrs - 1 + + +def account_status(topology_st, suffix, subtre, userid, nousrs, ulimit, tochck): + """Check account status for the given suffix, subtre, userid and nousrs""" + + while (nousrs > ulimit): + usrrdn = '{}{}'.format(userid, nousrs) + userdn = 'uid={},{},{}'.format(usrrdn, subtre, suffix) + if (tochck == "Enabled"): try: - topology_st.standalone.delete_s(USR_DN) + topology_st.standalone.simple_bind_s(userdn, USER_PW) except ldap.LDAPError as e: - log.error('Failed to delete {} :error- {}'.format(USR_DN, e.message['desc'])) + log.error('User {} is inactivated, expected 0 : error {}'.format(userdn, e.message['desc'])) raise - - request.addfinalizer(fin) + elif (tochck == "Disabled"): + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + topology_st.standalone.simple_bind_s(userdn, USER_PW) + log.error('User {} is not inactivated, expected error 19'.format(userdn)) + nousrs = nousrs - 1 -def test_inact_plugin(topology_st, accpolicy_local, users): - """Verify if user account is inactivated when accountInactivityLimit is exceeded. - User is created in the default SUFFIX. +def test_actNinact_local(topology_st, accpolicy_local): + """Verify if user account is inactivated when accountInactivityLimit is exceeded. User is created in the default suffix. :Feature: Account Policy Plugin :Setup: Standalone instance, Local account policy plugin configuration, accountInactivityLimit set to 15, Inactivate account by Account policy plugin - :Steps: 1. Configure account policy plugin with accpol_local for ou=people SUBTREE - 2. Set accountInactivityLimit to 15 - 3. Add few users to ou=people SUBTREE in the default SUFFIX - 4. Wait for 12 secs and run ldapsearch as normal user to check if its not inactivated, expected 0. - 5. Wait for 3 secs or till accountInactivityLimit is exceeded - 6. Run ldapsearch as normal user and check if its inactivated, expected error 19. + :Steps: 1. Configure account policy plugin with accpol_local for ou=people subtree + 2. Set accountInactivityLimit to 15 + 3. Add few users to ou=people subtre in the default suffix + 4. Wait for 14 secs and run ldapsearch as normal user to check if its not inactivated, expected 0. + 5. Wait for 2 secs or till accountInactivityLimit is exceeded + 6. Run ldapsearch as normal user and check if its inactivated, expected error 19. + 7. Sleep for +14 secs to check if accounts accessed at step4 are inactivated now :Assert: Should return error code 19 """ - log.info("AccountInactivityLimit set to 15. Account will be inactivated if not accessed in 15 secs") - log.info("Sleeping for 12 secs to check if account is not inactivated, expected value 0") - time.sleep(12) - for NUM in range(2, NOF_USERS): - USR_RDN = '{}{}'.format(USR_NAME, NUM) - USR_DN = 'uid={},{},{}'.format(USR_RDN, SUBTREE, SUFFIX) - try: - topology_st.standalone.simple_bind_s(USR_DN, USER_PW) - except ldap.LDAPError as e: - log.error('Checking if {} is inactivated: error {}'.format(USR_DN, e.message['desc'])) - raise + suffix = DEFAULT_SUFFIX + subtre = "ou=people" + userid = "inactusr" + userpw = USER_PW + nousrs = 3 + log.info('AccountInactivityLimit set to 15. Account will be inactivated if not accessed in 15 secs') + add_users(topology_st, suffix, subtre, userid, nousrs) + log.info('Sleeping for 14 secs to check account is not inactivated, expected value 0') + time.sleep(14) + log.info('Account should not be inactivated since AccountInactivityLimit not exceeded') + account_status(topology_st, suffix, subtre, userid, 3, 2, "Enabled") + log.info('Sleeping for 2 more secs to check if account is inactivated') + time.sleep(2) + account_status(topology_st, suffix, subtre, userid, 2, 0, "Disabled") + log.info('Sleeping +14 secs to check if account {}3 is inactivated'.format(userid)) + time.sleep(14) + account_status(topology_st, suffix, subtre, userid, 3, 2, "Disabled") + del_users(topology_st, suffix, subtre, userid, nousrs) + + +def test_noinact_local(topology_st, accpolicy_local): + """Verify if user account is inactivated when moved from ou=groups to ou=people subtree. + + :Feature: Account Policy Plugin + + :Setup: Standalone instance, Local account policy plugin configuration, + accountInactivityLimit set to 15, Inactivate account by Account policy plugin + + :Steps: 1. Add few users to ou=groups subtre in the default suffix, plugin configured to ou=people subtree only. + 2. Wait for 16 secs and run ldapsearch as normal user to check account is active, expected 0. + 3. Move users from ou=groups to ou=people subtree + 4. Sleep for 16 secs and check if entries are inactivated - USR_DN = 'uid={}1,{},{}'.format(USR_NAME, SUBTREE, SUFFIX) - log.info("Sleeping for 4 more secs to check if {} is inactivated, expected error 19".format(USR_DN)) - time.sleep(4) - with pytest.raises(ldap.CONSTRAINT_VIOLATION) as e: - topology_st.standalone.simple_bind_s(USR_DN, USER_PW) + :Assert: Should return error code 0 and 19 + """ - USR_DN = 'uid={}2,{},{}'.format(USR_NAME, SUBTREE, SUFFIX) - log.info("Checking if {} is not inactivated, expected value 0".format(USR_DN)) + suffix = DEFAULT_SUFFIX + subtre = "ou=groups" + userid = "nolockusr" + userpw = USER_PW + nousrs = 1 + log.info('Account should not be inactivated since the subtree is not configured') + add_users(topology_st, suffix, subtre, userid, nousrs) + log.info('Sleeping for 16 secs to check if account is not inactivated, expected value 0') + time.sleep(16) + account_status(topology_st, suffix, subtre, userid, nousrs, 0, "Enabled") + log.info('Moving users from ou=groups to ou=people subtree') try: - topology_st.standalone.simple_bind_s(USR_DN, USER_PW) + topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) + topology_st.standalone.rename_s('uid=nolockusr1,ou=groups,dc=example,dc=com', 'uid=nolockusr1', + 'ou=people,dc=example,dc=com') + except ldap.LDAPError as e: + log.error('Failed to move user uid=nolockusr1 from ou=groups to ou=people') + raise + subtre = "ou=people" + log.info('Then wait for 16 secs and check if entries are inactivated') + time.sleep(16) + account_status(topology_st, suffix, subtre, userid, nousrs, 0, "Disabled") + del_users(topology_st, suffix, subtre, userid, nousrs) + + +def test_inact_local(topology_st, accpolicy_local): + """Verify if user account is inactivated when users moved from ou=people to ou=groups subtree. + + :Feature: Account Policy Plugin + + :Setup: Standalone instance, Local account policy plugin configuration, + accountInactivityLimit set to 15, Inactivate account by Account policy plugin + + :Steps: 1. Add few users to ou=people subtre in the default suffix + 2. Wait for 14 secs and run ldapsearch as normal user to check if its not inactivated, expected 0. + 3. Move users from ou=people to ou=groups subtree + 4. Sleep for +2 secs and check if users are inactivated in ou=people subtree + 5. Check if users are not inactivated in ou=groups subtree + + :Assert: Should return error code 0 + """ + + suffix = DEFAULT_SUFFIX + subtre = "ou=people" + userid = "lockusr" + userpw = USER_PW + nousrs = 1 + log.info('Account should be inactivated since the subtree is configured') + add_users(topology_st, suffix, subtre, userid, nousrs) + log.info('Sleeping for 16 secs to check if account is inactivated, expected value 19') + time.sleep(14) + account_status(topology_st, suffix, subtre, userid, nousrs, 0, "Enabled") + log.info('Moving users from ou=people to ou=groups subtree') + try: + topology_st.standalone.simple_bind_s(DN_DM, PASSWORD) + topology_st.standalone.rename_s('uid=lockusr1,ou=people,dc=example,dc=com', 'uid=lockusr1', + 'ou=groups,dc=example,dc=com') except ldap.LDAPError as e: - log.error('Checking if {} is inactivated : error {}'.format(USR_DN, e.message['desc'])) + log.error('Failed to move user uid=lockusr1 from ou=groups to ou=people') raise - time.sleep(12) - for NUM in range(3, NOF_USERS): - USR_RDN = '{}{}'.format(USR_NAME, NUM) - USR_DN = 'uid={},{},{}'.format(USR_RDN, SUBTREE, SUFFIX) - log.info("Checking if {} is inactivated, expected error 19".format(USR_DN)) - with pytest.raises(ldap.CONSTRAINT_VIOLATION) as e: - topology_st.standalone.simple_bind_s(USR_DN, USER_PW) + log.info('Sleep for +2 secs and check users from both ou=people and ou=groups subtree') + time.sleep(2) + subtre = "ou=groups" + account_status(topology_st, suffix, subtre, userid, 1, 0, "Enabled") + del_users(topology_st, suffix, subtre, userid, nousrs) if __name__ == '__main__':
0
e8c56aaf2eadef1cc9aa6e8e39231ac9e31776c6
389ds/389-ds-base
Ticket lib389 3 - python 3 support Bug Description: Replication tests did not support python 3 Fix Description: Improve test running capability for python 3 including fixing master init. https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!)
commit e8c56aaf2eadef1cc9aa6e8e39231ac9e31776c6 Author: William Brown <[email protected]> Date: Mon Oct 16 23:21:35 2017 +1000 Ticket lib389 3 - python 3 support Bug Description: Replication tests did not support python 3 Fix Description: Improve test running capability for python 3 including fixing master init. https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!) diff --git a/dirsrvtests/tests/suites/replication/acceptance_test.py b/dirsrvtests/tests/suites/replication/acceptance_test.py index d7c1dfc1c..824a62784 100644 --- a/dirsrvtests/tests/suites/replication/acceptance_test.py +++ b/dirsrvtests/tests/suites/replication/acceptance_test.py @@ -10,8 +10,14 @@ import pytest from lib389.tasks import * from lib389.utils import * from lib389.topologies import topology_m4 as topo_m4 -from lib389._constants import * from . import get_repl_entries +from lib389.idm.user import UserAccount + +from lib389._constants import (BACKEND_NAME, DEFAULT_SUFFIX, LOG_REPLICA, REPLICA_RUV_FILTER, + ReplicaRole, REPLICATION_BIND_DN, REPLICATION_BIND_PW, + REPLICATION_BIND_METHOD, REPLICATION_TRANSPORT, defaultProperties, + RA_NAME, RA_BINDDN, RA_BINDPW, RA_METHOD, RA_TRANSPORT_PROT, + DN_DM, PASSWORD, LOG_DEFAULT, RA_ENABLED, RA_SCHEDULE) TEST_ENTRY_NAME = 'mmrepl_test' TEST_ENTRY_DN = 'uid={},{}'.format(TEST_ENTRY_NAME, DEFAULT_SUFFIX) @@ -32,30 +38,20 @@ def test_entry(topo_m4, request): """Add test entry to master1""" log.info('Adding entry {}'.format(TEST_ENTRY_DN)) - try: - topo_m4.ms["master1"].add_s(Entry((TEST_ENTRY_DN, { - 'objectclass': 'top person'.split(), - 'objectclass': 'organizationalPerson', - 'objectclass': 'inetorgperson', - 'cn': TEST_ENTRY_NAME, - 'sn': TEST_ENTRY_NAME, - 'uid': TEST_ENTRY_NAME, - 'userpassword': TEST_ENTRY_NAME - }))) - except ldap.LDAPError as e: - log.error('Failed to add entry (%s): error (%s)' % (TEST_ENTRY_DN, - e.message['desc'])) - raise e - def fin(): + test_user = UserAccount(topo_m4.ms["master1"], TEST_ENTRY_DN) + if test_user.exists(): log.info('Deleting entry {}'.format(TEST_ENTRY_DN)) - try: - topo_m4.ms["master1"].delete_s(TEST_ENTRY_DN) - except ldap.NO_SUCH_OBJECT: - log.info("Entry {} wasn't found".format(TEST_ENTRY_DN)) - - request.addfinalizer(fin) - + test_user.delete() + test_user.create(properties={ + 'uid': TEST_ENTRY_NAME, + 'cn': TEST_ENTRY_NAME, + 'sn': TEST_ENTRY_NAME, + 'userPassword': TEST_ENTRY_NAME, + 'uidNumber' : '1000', + 'gidNumber' : '2000', + 'homeDirectory' : '/home/mmrepl_test', + }) @pytest.fixture(scope="function") def new_suffix(topo_m4, request): @@ -129,46 +125,30 @@ def test_modify_entry(topo_m4, test_entry): """ log.info('Modifying entry {} - add operation'.format(TEST_ENTRY_DN)) - try: - topo_m4.ms["master1"].modify_s(TEST_ENTRY_DN, [(ldap.MOD_ADD, - 'mail', '{}@redhat.com'.format(TEST_ENTRY_NAME))]) - except ldap.LDAPError as e: - log.error('Failed to modify entry (%s): error (%s)' % (TEST_ENTRY_DN, - e.message['desc'])) - raise e + + test_user = UserAccount(topo_m4.ms["master1"], TEST_ENTRY_DN) + test_user.add('mail', '{}@redhat.com'.format(TEST_ENTRY_NAME)) time.sleep(1) - entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["mail"]) - assert all(entry["mail"] == "{}@redhat.com".format(TEST_ENTRY_NAME) - for entry in entries), "Entry attr {} wasn't replicated successfully".format(TEST_ENTRY_DN) + all_user = topo_m4.all_get_dsldapobject(TEST_ENTRY_DN, UserAccount) + for u in all_user: + assert "{}@redhat.com".format(TEST_ENTRY_NAME) in u.get_attr_vals_utf8('mail') log.info('Modifying entry {} - replace operation'.format(TEST_ENTRY_DN)) - try: - topo_m4.ms["master1"].modify_s(TEST_ENTRY_DN, [(ldap.MOD_REPLACE, - 'mail', '{}@greenhat.com'.format(TEST_ENTRY_NAME))]) - except ldap.LDAPError as e: - log.error('Failed to modify entry (%s): error (%s)' % (TEST_ENTRY_DN, - e.message['desc'])) - raise e + test_user.replace('mail', '{}@greenhat.com'.format(TEST_ENTRY_NAME)) time.sleep(1) - entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["mail"]) - assert all(entry["mail"] == "{}@greenhat.com".format(TEST_ENTRY_NAME) - for entry in entries), "Entry attr {} wasn't replicated successfully".format(TEST_ENTRY_DN) + all_user = topo_m4.all_get_dsldapobject(TEST_ENTRY_DN, UserAccount) + for u in all_user: + assert "{}@greenhat.com".format(TEST_ENTRY_NAME) in u.get_attr_vals_utf8('mail') log.info('Modifying entry {} - delete operation'.format(TEST_ENTRY_DN)) - try: - topo_m4.ms["master1"].modify_s(TEST_ENTRY_DN, [(ldap.MOD_DELETE, - 'mail', '{}@greenhat.com'.format(TEST_ENTRY_NAME))]) - except ldap.LDAPError as e: - log.error('Failed to modify entry (%s): error (%s)' % (TEST_ENTRY_DN, - e.message['desc'])) - raise e + test_user.remove('mail', '{}@greenhat.com'.format(TEST_ENTRY_NAME)) time.sleep(1) - entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["mail"]) - assert all(not entry["mail"] for entry in entries), "Entry attr {} wasn't replicated successfully".format( - TEST_ENTRY_DN) + all_user = topo_m4.all_get_dsldapobject(TEST_ENTRY_DN, UserAccount) + for u in all_user: + assert "{}@greenhat.com".format(TEST_ENTRY_NAME) not in u.get_attr_vals_utf8('mail') def test_delete_entry(topo_m4, test_entry): @@ -308,10 +288,10 @@ def test_modify_stripattrs(topo_m4): m1 = topo_m4.ms["master1"] agreement = m1.agreement.list(suffix=DEFAULT_SUFFIX)[0].dn - attr_value = 'modifiersname modifytimestamp' + attr_value = b'modifiersname modifytimestamp' log.info('Modify nsds5replicastripattrs with {}'.format(attr_value)) - m1.modify_s(agreement, [(ldap.MOD_REPLACE, 'nsds5replicastripattrs', attr_value)]) + m1.modify_s(agreement, [(ldap.MOD_REPLACE, 'nsds5replicastripattrs', [attr_value])]) log.info('Check nsds5replicastripattrs for {}'.format(attr_value)) entries = m1.search_s(agreement, ldap.SCOPE_BASE, "objectclass=*", ['nsds5replicastripattrs']) @@ -387,16 +367,13 @@ def test_many_attrs(topo_m4, test_entry): """ m1 = topo_m4.ms["master1"] - add_list = map(lambda x: "test{}".format(x), range(10)) - delete_list = map(lambda x: "test{}".format(x), [0, 4, 7, 9]) + add_list = ensure_list_bytes(map(lambda x: "test{}".format(x), range(10))) + delete_list = ensure_list_bytes(map(lambda x: "test{}".format(x), [0, 4, 7, 9])) + test_user = UserAccount(topo_m4.ms["master1"], TEST_ENTRY_DN) log.info('Modifying entry {} - 10 add operations'.format(TEST_ENTRY_DN)) for add_name in add_list: - try: - m1.modify_s(TEST_ENTRY_DN, [(ldap.MOD_ADD, 'description', add_name)]) - except ldap.LDAPError as e: - log.error('Failed to modify entry (%s): error (%s)' % (TEST_ENTRY_DN, e.message['desc'])) - raise e + test_user.add('description', add_name) log.info('Check that everything was properly replicated after an add operation') entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["description"]) @@ -405,11 +382,7 @@ def test_many_attrs(topo_m4, test_entry): log.info('Modifying entry {} - 4 delete operations for {}'.format(TEST_ENTRY_DN, str(delete_list))) for delete_name in delete_list: - try: - m1.modify_s(TEST_ENTRY_DN, [(ldap.MOD_DELETE, 'description', delete_name)]) - except ldap.LDAPError as e: - log.error('Failed to modify entry (%s): error (%s)' % (TEST_ENTRY_DN, e.message['desc'])) - raise e + test_user.remove('description', delete_name) log.info('Check that everything was properly replicated after a delete operation') entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["description"]) @@ -419,6 +392,112 @@ def test_many_attrs(topo_m4, test_entry): assert value not in delete_list +def test_double_delete(topo_m4, test_entry): + """Check that double delete of the entry doesn't crash server + + :ID: 3496c82d-636a-48c9-973c-2455b12164cc + :feature: Multi master replication + :setup: Four masters replication setup, a test entry + :steps: 1. Delete the entry + 2. Delete the entry on the second master + 3. Check that server is alive + :expectedresults: Server hasn't crash + """ + + log.info('Deleting entry {} from master1'.format(TEST_ENTRY_DN)) + topo_m4.ms["master1"].delete_s(TEST_ENTRY_DN) + + log.info('Deleting entry {} from master2'.format(TEST_ENTRY_DN)) + try: + topo_m4.ms["master2"].delete_s(TEST_ENTRY_DN) + except ldap.NO_SUCH_OBJECT: + log.info("Entry {} wasn't found master2. It is expected.".format(TEST_ENTRY_DN)) + + log.info('Make searches to check if server is alive') + entries = get_repl_entries(topo_m4, TEST_ENTRY_NAME, ["uid"]) + assert not entries, "Entry deletion {} wasn't replicated successfully".format(TEST_ENTRY_DN) + + +def test_password_repl_error(topo_m4, test_entry): + """Check that error about userpassword replication is properly logged + + :ID: 714130ff-e4f0-4633-9def-c1f4b24abfef + :feature: Multi master replication + :setup: Four masters replication setup, a test entry + :steps: 1. Change userpassword on master 1 + 2. Restart the servers to flush the logs + 3. Check the error log for an replication error + :expectedresults: We don't have a replication error in the error log + """ + + m1 = topo_m4.ms["master1"] + m2 = topo_m4.ms["master2"] + TEST_ENTRY_NEW_PASS = 'new_{}'.format(TEST_ENTRY_NAME) + + log.info('Clean the error log') + m2.deleteErrorLogs() + + log.info('Set replication loglevel') + m2.setLogLevel(LOG_REPLICA) + + log.info('Modifying entry {} - change userpassword on master 2'.format(TEST_ENTRY_DN)) + test_user_m1 = UserAccount(topo_m4.ms["master1"], TEST_ENTRY_DN) + test_user_m2 = UserAccount(topo_m4.ms["master2"], TEST_ENTRY_DN) + test_user_m3 = UserAccount(topo_m4.ms["master3"], TEST_ENTRY_DN) + test_user_m4 = UserAccount(topo_m4.ms["master4"], TEST_ENTRY_DN) + + test_user_m1.set('userpassword', TEST_ENTRY_NEW_PASS) + + log.info('Restart the servers to flush the logs') + for num in range(1, 5): + topo_m4.ms["master{}".format(num)].restart(timeout=10) + + m1_conn = test_user_m1.bind(TEST_ENTRY_NEW_PASS) + m2_conn = test_user_m2.bind(TEST_ENTRY_NEW_PASS) + m3_conn = test_user_m3.bind(TEST_ENTRY_NEW_PASS) + m4_conn = test_user_m4.bind(TEST_ENTRY_NEW_PASS) + + log.info('Check the error log for the error with {}'.format(TEST_ENTRY_DN)) + assert not m2.ds_error_log.match('.*can.t add a change for uid={}.*'.format(TEST_ENTRY_NAME)) + + +def test_invalid_agmt(topo_m4): + """Test adding that an invalid agreement is properly rejected and does not crash the server + + :id: 6c3b2a7e-edcd-4327-a003-6bd878ff722b + :setup: MMR with four masters + :steps: + 1. Add invalid agreement (nsds5ReplicaEnabled set to invalid value) + 2. Verify the server is still running + :expectedresults: + 1. Invalid repl agreement should be rejected + 2. Server should be still running + """ + m1 = topo_m4.ms["master1"] + + # Add invalid agreement (nsds5ReplicaEnabled set to invalid value) + AGMT_DN = 'cn=whatever,cn=replica,cn="dc=example,dc=com",cn=mapping tree,cn=config' + try: + invalid_props = {RA_ENABLED: 'True', # Invalid value + RA_SCHEDULE: '0001-2359 0123456'} + m1.agreement.create(suffix=DEFAULT_SUFFIX, host='localhost', port=389, properties=invalid_props) + except ldap.UNWILLING_TO_PERFORM: + m1.log.info('Invalid repl agreement correctly rejected') + except ldap.LDAPError as e: + m1.log.fatal('Got unexpected error adding invalid agreement: ' + str(e)) + assert False + else: + m1.log.fatal('Invalid agreement was incorrectly accepted by the server') + assert False + + # Verify the server is still running + try: + m1.simple_bind_s(DN_DM, PASSWORD) + except ldap.LDAPError as e: + m1.log.fatal('Failed to bind: ' + str(e)) + assert False + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode diff --git a/dirsrvtests/tests/suites/replication/single_master_test.py b/dirsrvtests/tests/suites/replication/single_master_test.py index 44cd5cf53..b1cba70a2 100644 --- a/dirsrvtests/tests/suites/replication/single_master_test.py +++ b/dirsrvtests/tests/suites/replication/single_master_test.py @@ -174,9 +174,9 @@ def test_lastupdate_attr_before_init(topo_nr, replica_without_init): "nsds5replicaLastUpdateEnd", "nsds5replicaLastUpdateStatus"])[0] - assert agmt["nsds5replicaLastUpdateStart"] == "19700101000000Z" - assert agmt["nsds5replicaLastUpdateEnd"] == "19700101000000Z" - assert "Replica acquired successfully" not in agmt["nsds5replicaLastUpdateStatus"] + assert agmt["nsds5replicaLastUpdateStart"] == b"19700101000000Z" + assert agmt["nsds5replicaLastUpdateEnd"] == b"19700101000000Z" + assert b"Replica acquired successfully" not in agmt["nsds5replicaLastUpdateStatus"] if __name__ == '__main__': diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 39e504f30..b08c09b43 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -2282,7 +2282,7 @@ class DirSrv(SimpleLDAPObject, object): @raise None ''' - test_value = ('test replication from ' + self.serverid + ' to ' + + test_value = ensure_bytes('test replication from ' + self.serverid + ' to ' + replicas[0].serverid + ': ' + str(int(time.time()))) self.modify_s(suffix, [(ldap.MOD_REPLACE, 'description', test_value)]) diff --git a/src/lib389/lib389/agreement.py b/src/lib389/lib389/agreement.py index 822f9a33c..b0ab88184 100644 --- a/src/lib389/lib389/agreement.py +++ b/src/lib389/lib389/agreement.py @@ -679,14 +679,8 @@ class Agreement(object): """ self.log.info("Pausing replication %s" % agmtdn) - mod = [( - ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', ['off'])] - try: - self.conn.modify_s(agmtdn, mod) - except ldap.LDAPError: - # before 1.2.11, no support for nsds5ReplicaEnabled - # use schedule hack - self.schedule(interval) + mod = [(ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', [b'off'])] + self.conn.modify_s(ensure_str(agmtdn), mod) # Allow a little time for repl agmt thread to stop time.sleep(5) @@ -711,14 +705,8 @@ class Agreement(object): """ self.log.info("Resuming replication %s" % agmtdn) - mod = [( - ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', ['on'])] - try: - self.conn.modify_s(agmtdn, mod) - except ldap.LDAPError: - # before 1.2.11, no support for nsds5ReplicaEnabled - # use schedule hack - self.schedule(interval) + mod = [(ldap.MOD_REPLACE, 'nsds5ReplicaEnabled', [b'on'])] + self.conn.modify_s(ensure_str(agmtdn), mod) # Allow a little time for the repl agmt thread to start time.sleep(2) diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index cdd0a9729..48cbcd714 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -17,6 +17,7 @@ from lib389._replication import RUV from lib389.repltools import ReplTools from lib389 import DirSrv, Entry, NoSuchEntryError, InvalidArgumentError from lib389._mapped_object import DSLdapObjects, DSLdapObject +from lib389.idm.domain import Domain class ReplicaLegacy(object): @@ -624,7 +625,7 @@ class ReplicaLegacy(object): @param agmtdn - agreement dn """ self.log.info("Starting async replication %s" % agmtdn) - mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', 'start')] + mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', b'start')] self.conn.modify_s(agmtdn, mod) def keep_in_sync(self, agmtdn): @@ -1070,11 +1071,11 @@ class Replica(DSLdapObject): if not refresh: # done - check status if not status: print("No status yet") - elif status.find("replica busy") > -1: + elif status.find(b"replica busy") > -1: print("Update failed - replica busy - status", status) done = True hasError = 2 - elif status.find("Total update succeeded") > -1: + elif status.find(b"Total update succeeded") > -1: print("Update succeeded: status ", status) done = True elif inprogress.lower() == 'true': @@ -1134,7 +1135,7 @@ class Replica(DSLdapObject): """ self._log.info("Starting async replication %s" % agmtdn) - mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', 'start')] + mod = [(ldap.MOD_ADD, 'nsds5BeginReplicaRefresh', b'start')] self._instance.modify_s(agmtdn, mod) def get_ruv_entry(self): @@ -1169,23 +1170,23 @@ class Replica(DSLdapObject): """ # Generate a unique test value - test_value = ('test replication from ' + self._instance.serverid + + test_value = ensure_bytes('test replication from ' + self._instance.serverid + ' to ' + replica_dirsrvs[0].serverid + ': ' + str(int(time.time()))) - self._instance.modify_s(self._suffix, - [(ldap.MOD_REPLACE, 'description', test_value)]) + + my_domain = Domain(self._instance, self._suffix) + my_domain.replace('description', test_value) for replica in replica_dirsrvs: + r_domain = Domain(replica, self._suffix) loop = 0 replicated = False while loop <= 30: # Wait 60 seconds before giving up try: + r_test_values = r_domain.get_attr_vals_bytes('description') - entry = replica.getEntry(self._suffix, - ldap.SCOPE_BASE, - '(objectclass=*)') - if entry.hasValue('description', test_value): + if test_value in r_test_values: replicated = True break except ldap.LDAPError as e: @@ -1198,8 +1199,7 @@ class Replica(DSLdapObject): return False # All is good, remove the test mod from the suffix entry - self._instance.modify_s(self._suffix, - [(ldap.MOD_DELETE, 'description', test_value)]) + my_domain.remove('description', None) return True diff --git a/src/lib389/lib389/topologies.py b/src/lib389/lib389/topologies.py index 674f1d0bc..69c71ee10 100644 --- a/src/lib389/lib389/topologies.py +++ b/src/lib389/lib389/topologies.py @@ -116,7 +116,8 @@ def create_topology(topo_dict): for replica_from, inst_from in replica_dict.items(): if replica_from.get_role() == ReplicaRole.MASTER: agmts = inst_from.agreement.list(DEFAULT_SUFFIX) - map(lambda agmt: replica_from.start_and_wait(agmt.dn), agmts) + for r in map(lambda agmt: replica_from.start_and_wait(agmt.dn), agmts): + assert r == 0 break # Clear out the tmp dir @@ -162,6 +163,13 @@ class TopologyMain(object): for agreement in inst.agreement.list(suffix=DEFAULT_SUFFIX): inst.agreement.resume(agreement.dn) + def all_get_dsldapobject(self, dn, otype): + result = [] + for inst in self.all_insts.values(): + o = otype(inst, dn) + result.append(o) + return result + @pytest.fixture(scope="module") def topology_st(request): @@ -218,7 +226,7 @@ def topology_m1c1(request): topology = create_topology({ReplicaRole.MASTER: 1, ReplicaRole.CONSUMER: 1}) replicas = Replicas(topology.ms["master1"]) - replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) + assert replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) def fin(): if DEBUGGING: @@ -236,7 +244,7 @@ def topology_m2(request): topology = create_topology({ReplicaRole.MASTER: 2}) replicas = Replicas(topology.ms["master1"]) - replicas.test(DEFAULT_SUFFIX, topology.ms["master2"]) + assert replicas.test(DEFAULT_SUFFIX, topology.ms["master2"]) def fin(): if DEBUGGING: @@ -254,7 +262,7 @@ def topology_m3(request): topology = create_topology({ReplicaRole.MASTER: 3}) replicas = Replicas(topology.ms["master1"]) - replicas.test(DEFAULT_SUFFIX, topology.ms["master3"]) + assert replicas.test(DEFAULT_SUFFIX, topology.ms["master3"]) def fin(): if DEBUGGING: @@ -272,7 +280,7 @@ def topology_m4(request): topology = create_topology({ReplicaRole.MASTER: 4}) replicas = Replicas(topology.ms["master1"]) - replicas.test(DEFAULT_SUFFIX, topology.ms["master4"]) + assert replicas.test(DEFAULT_SUFFIX, topology.ms["master4"]) def fin(): if DEBUGGING: @@ -291,7 +299,7 @@ def topology_m2c2(request): topology = create_topology({ReplicaRole.MASTER: 2, ReplicaRole.CONSUMER: 2}) replicas = Replicas(topology.ms["master1"]) - replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) + assert replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) def fin(): if DEBUGGING: @@ -366,7 +374,7 @@ def topology_m1h1c1(request): # Check replication is working... replicas = Replicas(master) - replicas.test(DEFAULT_SUFFIX, consumer) + assert replicas.test(DEFAULT_SUFFIX, consumer) # Clear out the tmp dir master.clearTmpDir(__file__)
0
ea408efe551ad837b08423f6d32b5433ab8dfe2b
389ds/389-ds-base
fix compiler warnings - unused vars/funcs, invalid casts This commit fixes many compiler warnings, mostly for things like unused variables, functions, goto labels. One place was using csngen_free instead of csn_free. A couple of places were using casts incorrectly, and several places needed some casts added. Tested on: RHEL5 x86_64, Fedora 14 x86_64 Reviewed by: nkinder (Thanks!)
commit ea408efe551ad837b08423f6d32b5433ab8dfe2b Author: Rich Megginson <[email protected]> Date: Tue Aug 31 21:17:30 2010 -0600 fix compiler warnings - unused vars/funcs, invalid casts This commit fixes many compiler warnings, mostly for things like unused variables, functions, goto labels. One place was using csngen_free instead of csn_free. A couple of places were using casts incorrectly, and several places needed some casts added. Tested on: RHEL5 x86_64, Fedora 14 x86_64 Reviewed by: nkinder (Thanks!) diff --git a/include/base/dbtbase.h b/include/base/dbtbase.h index 380bfa064..801cc07ac 100644 --- a/include/base/dbtbase.h +++ b/include/base/dbtbase.h @@ -43,7 +43,9 @@ #define LIBRARY_NAME "base" +#ifdef RESOURCE_STR static char dbtbaseid[] = "$DBT: base referenced v1 $"; +#endif #include "i18n.h" diff --git a/include/libaccess/aclproto.h b/include/libaccess/aclproto.h index 7562c7124..5f273842b 100644 --- a/include/libaccess/aclproto.h +++ b/include/libaccess/aclproto.h @@ -144,7 +144,6 @@ NSAPI_PUBLIC int ACL_Init(void); NSAPI_PUBLIC int ACL_InitPostMagnus(void); NSAPI_PUBLIC int ACL_LateInitPostMagnus(void); NSAPI_PUBLIC void ACL_ListHashUpdate(ACLListHandle_t **acllistp); -NSAPI_PUBLIC int ACL_ReadDbMapFile(NSErr_t *errp, const char *map_file, int default_only); NSAPI_PUBLIC int ACL_MethodNamesGet(NSErr_t *errp, char ***names, int *count); NSAPI_PUBLIC int ACL_MethodNamesFree(NSErr_t *errp, char **names, int count); diff --git a/include/libaccess/dbtlibaccess.h b/include/libaccess/dbtlibaccess.h index 1d78a9bd2..90b943d05 100644 --- a/include/libaccess/dbtlibaccess.h +++ b/include/libaccess/dbtlibaccess.h @@ -43,7 +43,9 @@ #define LIBRARY_NAME "libaccess" +#ifdef RESOURCE_STR static char dbtlibaccessid[] = "$DBT: libaccess referenced v1 $"; +#endif /* RESOURCE_STR */ #include "i18n.h" diff --git a/ldap/servers/plugins/chainingdb/cb_config.c b/ldap/servers/plugins/chainingdb/cb_config.c index b399ed7b2..bc12cd7dd 100644 --- a/ldap/servers/plugins/chainingdb/cb_config.c +++ b/ldap/servers/plugins/chainingdb/cb_config.c @@ -632,8 +632,7 @@ static int cb_parse_config_entry(cb_backend * cb, Slapi_Entry *e) } else if ( !strcasecmp ( attr_name, CB_CONFIG_GLOBAL_DEBUG )) { i = slapi_attr_first_value(attr, &sval); - if (i != -1 ) { - (struct berval *) slapi_value_get_berval(sval); + if ((i != -1) && slapi_value_get_berval(sval)) { /* any value */ cb_set_debug(1); } diff --git a/ldap/servers/plugins/deref/deref.c b/ldap/servers/plugins/deref/deref.c index 5bbab1389..e7fdaa5cb 100644 --- a/ldap/servers/plugins/deref/deref.c +++ b/ldap/servers/plugins/deref/deref.c @@ -380,7 +380,7 @@ deref_parse_ctrl_value(DerefSpecList *speclist, const struct berval *ctrlbv, int PR_ASSERT(ctrlbv && ctrlbv->bv_val && ctrlbv->bv_len && ldapcode && ldaperrtext); - ber = ber_init(ctrlbv); + ber = ber_init((struct berval *)ctrlbv); for (tag = ber_first_element(ber, &len, &last); (tag != LBER_ERROR) && (tag != LBER_END_OF_SEQORSET); tag = ber_next_element(ber, &len, last)) { diff --git a/ldap/servers/plugins/dna/dna.c b/ldap/servers/plugins/dna/dna.c index 5838cd747..558e61382 100644 --- a/ldap/servers/plugins/dna/dna.c +++ b/ldap/servers/plugins/dna/dna.c @@ -1004,7 +1004,6 @@ dna_parse_config_entry(Slapi_Entry * e, int apply) break; } - next: list = PR_NEXT_LINK(list); if (dna_global_config == list) { @@ -1772,7 +1771,7 @@ dna_first_free_value(struct configEntry *config_entry, char *filter = NULL; char *prefix; int multitype; - int result, status, filterlen; + int result, status; PRUint64 tmpval, sval, i; char *strval = NULL; diff --git a/ldap/servers/plugins/pwdstorage/smd5_pwd.c b/ldap/servers/plugins/pwdstorage/smd5_pwd.c index cef3ee378..48baa24b5 100644 --- a/ldap/servers/plugins/pwdstorage/smd5_pwd.c +++ b/ldap/servers/plugins/pwdstorage/smd5_pwd.c @@ -66,8 +66,8 @@ smd5_pw_cmp( const char *userpwd, const char *dbpwd ) unsigned int outLen; unsigned char userhash[MD5_LENGTH]; int hash_len; - unsigned char quick_dbhash[MD5_LENGTH + MD5_DEFAULT_SALT_LENGTH + 1]; - unsigned char *dbhash = quick_dbhash; + char quick_dbhash[MD5_LENGTH + MD5_DEFAULT_SALT_LENGTH + 1]; + char *dbhash = quick_dbhash; struct berval salt; char *hashresult = NULL; @@ -83,7 +83,7 @@ smd5_pw_cmp( const char *userpwd, const char *dbpwd ) */ hash_len = pwdstorage_base64_decode_len(dbpwd, 0); if ( hash_len >= sizeof(quick_dbhash) ) { /* get more space: */ - dbhash = (unsigned char*) slapi_ch_calloc( hash_len + 1, sizeof(char) ); + dbhash = (char*) slapi_ch_calloc( hash_len + 1, sizeof(char) ); if ( dbhash == NULL ) goto loser; } else { memset( quick_dbhash, 0, sizeof(quick_dbhash) ); diff --git a/ldap/servers/plugins/uiduniq/utils.c b/ldap/servers/plugins/uiduniq/utils.c index e99573bf3..49660897b 100644 --- a/ldap/servers/plugins/uiduniq/utils.c +++ b/ldap/servers/plugins/uiduniq/utils.c @@ -62,11 +62,6 @@ static char *plugin_name = "utils"; -/* - * Lock for updating a counter (global for all counters) - */ -static Slapi_Mutex *counter_lock = NULL; - /* ------------------------------------------------------------ */ /* * op_error - Record (and report) an operational error. diff --git a/ldap/servers/plugins/usn/usn.c b/ldap/servers/plugins/usn/usn.c index 75c80ba23..5dd5122b7 100644 --- a/ldap/servers/plugins/usn/usn.c +++ b/ldap/servers/plugins/usn/usn.c @@ -290,7 +290,7 @@ usn_preop_delete(Slapi_PBlock *pb) if (CSN_SUCCESS != rc) { slapi_log_error(SLAPI_LOG_FATAL, USN_PLUGIN_SUBSYSTEM, "usn_preop_delete: csngen_new failed (%d)\n", rc); - csngen_free(&csn); + csn_free(&csn); goto bail; } operation_set_csn(op, csn); diff --git a/ldap/servers/slapd/back-ldbm/import-threads.c b/ldap/servers/slapd/back-ldbm/import-threads.c index 60a92b380..12018dbf3 100644 --- a/ldap/servers/slapd/back-ldbm/import-threads.c +++ b/ldap/servers/slapd/back-ldbm/import-threads.c @@ -1321,7 +1321,7 @@ upgradedn_producer(void *param) /* call post-entry plugin */ plugin_call_entryfetch_plugins((char **)&data.dptr, &data.dsize); - slapi_ch_free_string((void**)&ecopy); + slapi_ch_free_string(&ecopy); ecopy = (char *)slapi_ch_malloc(data.dsize + 1); memcpy(ecopy, data.dptr, data.dsize); *(ecopy + data.dsize) = '\0'; @@ -1732,7 +1732,7 @@ error: info->state = ABORTED; done: - slapi_ch_free_string((void**)&ecopy); + slapi_ch_free_string(&ecopy); slapi_ch_free(&(data.data)); } diff --git a/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c b/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c index 83130207f..deb818d64 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c @@ -1014,7 +1014,7 @@ attrcrypt_decrypt_index_key(backend *be, rc = -1; goto bail; } - (*out) = ber_bvdup(out_bv); + (*out) = ber_bvdup((struct berval *)out_bv); if (NULL == *out) { rc = -1; } diff --git a/ldap/servers/slapd/back-ldbm/ldbm_usn.c b/ldap/servers/slapd/back-ldbm/ldbm_usn.c index 2bb64bc24..2261e42d1 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_usn.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_usn.c @@ -81,7 +81,7 @@ ldbm_usn_init(struct ldbminfo *li) sdn = slapi_get_next_suffix_ext( &node, 0 )) { be = slapi_mapping_tree_find_backend_for_sdn(sdn); slapi_log_error(SLAPI_LOG_BACKLDBM, "ldbm_usn_init", - "backend: %s \n", be->be_name, isglobal?"(global mode)":""); + "backend: %s%s\n", be->be_name, isglobal?" (global mode)":""); rc = usn_get_last_usn(be, &last_usn); if (0 == rc) { /* only when the last usn is available */ if (isglobal) { @@ -201,7 +201,6 @@ int ldbm_set_last_usn(Slapi_Backend *be) { PRUint64 last_usn = 0; - PRUint64 current_usn = 0; int isglobal = config_get_entryusn_global(); int rc = -1; diff --git a/ldap/servers/slapd/back-ldbm/perfctrs.c b/ldap/servers/slapd/back-ldbm/perfctrs.c index 521ba1f2c..bb5ba00fe 100644 --- a/ldap/servers/slapd/back-ldbm/perfctrs.c +++ b/ldap/servers/slapd/back-ldbm/perfctrs.c @@ -211,7 +211,6 @@ void perfctrs_init(struct ldbminfo *li, perfctrs_private **ret_priv) *ret_priv = priv; return; -error: #if !defined(_WIN32) if (priv) slapi_ch_free((void**)&priv->memory); #endif diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index 8cf988969..77b08cddb 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -2020,7 +2020,7 @@ mozldap_ldap_explode( const char *dn, const int notypes, const int nametype ) return( NULL ); } else if ( count >= 8 ) { if (( rdns = (char **)slapi_ch_realloc( - rdns, (count+1) * + (char *)rdns, (count+1) * sizeof( char *))) == NULL ) return( NULL ); } diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index ed146c445..6524c800e 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -1368,7 +1368,7 @@ void *pagedresults_get_search_result(Connection *conn); int pagedresults_set_search_result(Connection *conn, void *sr); int pagedresults_get_search_result_count(Connection *conn); int pagedresults_set_search_result_count(Connection *conn, int cnt); -int pagedresults_get_search_result_get_size_estimate(Connection *conn); +int pagedresults_get_search_result_set_size_estimate(Connection *conn); int pagedresults_set_search_result_set_size_estimate(Connection *conn, int cnt); int pagedresults_get_with_sort(Connection *conn); int pagedresults_set_with_sort(Connection *conn, int flags); diff --git a/ldap/servers/slapd/psearch.c b/ldap/servers/slapd/psearch.c index afb3f1873..c19d34f4a 100644 --- a/ldap/servers/slapd/psearch.c +++ b/ldap/servers/slapd/psearch.c @@ -462,7 +462,7 @@ psearch_alloc() if (( ps->ps_lock = PR_NewLock()) == NULL ) { LDAPDebug( LDAP_DEBUG_ANY, "psearch_add: cannot create new lock. " "Persistent search abandoned.\n", 0, 0, 0 ); - slapi_ch_free(&ps); + slapi_ch_free((void **)&ps); return( NULL ); } ps->ps_tid = (PRThread *) NULL; diff --git a/ldap/servers/slapd/tools/dbscan.c b/ldap/servers/slapd/tools/dbscan.c index dfe811e1c..0c36ddcee 100644 --- a/ldap/servers/slapd/tools/dbscan.c +++ b/ldap/servers/slapd/tools/dbscan.c @@ -814,7 +814,7 @@ display_entryrdn_self(DB *db, ID id, const char *nrdn, int indent) rc = cursor->c_get(cursor, &key, &data, DB_SET); if (rc) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key.data, db_strerror(rc), rc); + "(%d)\n", (char *)key.data, db_strerror(rc), rc); goto bail; } @@ -859,7 +859,7 @@ display_entryrdn_parent(DB *db, ID id, const char *nrdn, int indent) rc = cursor->c_get(cursor, &key, &data, DB_SET); if (rc) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key.data, db_strerror(rc), rc); + "(%d)\n", (char *)key.data, db_strerror(rc), rc); goto bail; } @@ -908,10 +908,10 @@ display_entryrdn_children(DB *db, ID id, const char *nrdn, int indent) fprintf(stderr, "Entryrdn index is corrupt; " "data item for key %s is too large for our " "buffer (need=%d actual=%d)\n", - key.data, data.size, data.ulen); + (char *)key.data, data.size, data.ulen); } else if (rc != DB_NOTFOUND) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key.data, db_strerror(rc), rc); + "(%d)\n", (char *)key.data, db_strerror(rc), rc); } goto bail; } @@ -932,10 +932,10 @@ display_entryrdn_children(DB *db, ID id, const char *nrdn, int indent) fprintf(stderr, "Entryrdn index is corrupt; " "data item for key %s is too large for our " "buffer (need=%d actual=%d)\n", - key.data, data.size, data.ulen); + (char *)key.data, data.size, data.ulen); } else if (rc != DB_NOTFOUND) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key.data, db_strerror(rc), rc); + "(%d)\n", (char *)key.data, db_strerror(rc), rc); } } bail: @@ -961,7 +961,7 @@ display_entryrdn_item(DB *db, DBC *cursor, DBT *key) rc = cursor->c_get(cursor, key, &data, DB_SET); if (rc) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key->data, db_strerror(rc), rc); + "(%d)\n", (char *)key->data, db_strerror(rc), rc); return; } @@ -986,12 +986,12 @@ next: fprintf(stderr, "Entryrdn index is corrupt; " "data item for key %s is too large for our " "buffer (need=%d actual=%d)\n", - key->data, data.size, data.ulen); + (char *)key->data, data.size, data.ulen); } else { if (rc != DB_NOTFOUND) { fprintf(stderr, "Failed to position cursor " "at the key: %s: %s (%d)\n", - key->data, db_strerror(rc), rc); + (char *)key->data, db_strerror(rc), rc); } } goto bail; @@ -1021,11 +1021,11 @@ next: fprintf(stderr, "Entryrdn index is corrupt; " "data item for key %s is too large for our " "buffer (need=%d actual=%d)\n", - key->data, data.size, data.ulen); + (char *)key->data, data.size, data.ulen); goto bail; } else if (rc != DB_NOTFOUND) { fprintf(stderr, "Failed to position cursor at the key: %s: %s " - "(%d)\n", key->data, db_strerror(rc), rc); + "(%d)\n", (char *)key->data, db_strerror(rc), rc); goto bail; } flags = DB_NEXT|DB_MULTIPLE; diff --git a/ldap/servers/slapd/valueset.c b/ldap/servers/slapd/valueset.c index 22ffb4aac..a2ae334f5 100644 --- a/ldap/servers/slapd/valueset.c +++ b/ldap/servers/slapd/valueset.c @@ -303,7 +303,7 @@ valuearray_get_bervalarray(Slapi_Value **cvals,struct berval ***bvals) *bvals = (struct berval **)slapi_ch_malloc((n + 1) * sizeof(struct berval *)); for(i=0;i<n;i++) { - (*bvals)[i] = ber_bvdup(slapi_value_get_berval(cvals[i])); + (*bvals)[i] = ber_bvdup((struct berval *)slapi_value_get_berval(cvals[i])); } (*bvals)[i] = NULL; } diff --git a/ldap/servers/slapd/vattr.c b/ldap/servers/slapd/vattr.c index 025c71e06..df8954935 100644 --- a/ldap/servers/slapd/vattr.c +++ b/ldap/servers/slapd/vattr.c @@ -1650,7 +1650,6 @@ int slapi_vattrspi_regattr(vattr_sp_handle *h,char *type_name_to_register, char* ret = vattr_map_sp_insert(type_to_add,h,hint); -done: slapi_sdn_done(&original_dn); if(free_type_to_add) { diff --git a/lib/base/crit.cpp b/lib/base/crit.cpp index 1a1286c23..2aa9b5ac4 100644 --- a/lib/base/crit.cpp +++ b/lib/base/crit.cpp @@ -56,13 +56,7 @@ #include "crit.h" #include "pool.h" -#include "base/dbtbase.h" - #ifdef USE_NSPR -/* -#include "prmon.h" -#include "private/primpl.h" -*/ #include "nspr.h" #include "prthread.h" diff --git a/lib/base/ereport.cpp b/lib/base/ereport.cpp index ba3df4e58..e6b77685d 100644 --- a/lib/base/ereport.cpp +++ b/lib/base/ereport.cpp @@ -54,8 +54,6 @@ #include "ereport.h" #include "slapi-plugin.h" -#include "base/dbtbase.h" - #include <stdarg.h> #include <stdio.h> /* vsprintf */ #include <string.h> /* strcpy */ diff --git a/lib/base/util.cpp b/lib/base/util.cpp index d3a7c330b..b198154ee 100644 --- a/lib/base/util.cpp +++ b/lib/base/util.cpp @@ -56,9 +56,6 @@ #include "base/util.h" -#include "base/dbtbase.h" - - #ifdef XP_UNIX #include <sys/types.h> #endif /* WIN32 */ diff --git a/lib/ldaputil/certmap.c b/lib/ldaputil/certmap.c index a8cb6cb2c..9c6b2bad2 100644 --- a/lib/ldaputil/certmap.c +++ b/lib/ldaputil/certmap.c @@ -234,94 +234,6 @@ NSAPI_PUBLIC int ldapu_list_add_info (LDAPUList_t *list, void *info) return ldapu_list_add_node(list, node); } -static int ldapu_list_remove_node (LDAPUList_t *list, LDAPUListNode_t *node) -{ - if (list->head == node) { - list->head = node->next; - if (list->tail == node) list->tail = 0; /* removed the only node */ - } - else if (list->tail == node) { - list->tail = node->prev; - } - else { - node->prev->next = node->next; - node->next->prev = node->prev; - } - - node->next = 0; - node->prev = 0; - return LDAPU_SUCCESS; -} - -static int ldapu_list_copy (const LDAPUList_t *from, LDAPUList_t **to, - LDAPUListNodeFn_t copy_fn) -{ - LDAPUListNode_t *node = from->head; - LDAPUListNode_t *newnode; - LDAPUList_t *list = NULL; - int rv; - - *to = 0; - rv = ldapu_list_alloc(&list); - if (rv != LDAPU_SUCCESS) goto error; - - while(node) { - newnode = (LDAPUListNode_t *)(*copy_fn)(node->info, 0); - if (!newnode) { - rv = LDAPU_ERR_OUT_OF_MEMORY; - goto error; - } - - rv = ldapu_list_add_info(list, newnode); - if (rv != LDAPU_SUCCESS) goto error; - - node = node->next; - } - - *to = list; - goto done; - -error: - if (list) ldapu_propval_list_free(list); - -done: - return rv; -} - -static int ldapu_list_find_node (const LDAPUList_t *list, - LDAPUListNode_t **found, - LDAPUListNodeFn_t find_fn, - void *find_arg) -{ - LDAPUListNode_t *node = list->head; - - while(node) { - if ((*find_fn)(node->info, find_arg) == LDAPU_SUCCESS) { - *found = node; - return LDAPU_SUCCESS; - } - node = node->next; - } - - return LDAPU_ERR_CERTMAP_INFO_MISSING; -} - -static int ldapu_list_print (LDAPUList_t *list, LDAPUListNodeFn_t print_fn, - LDAPUPrintInfo_t *pinfo) -{ - LDAPUListNode_t *node = list->head; - int rv; - - while(node) { - uintptr_t retval = (uintptr_t)(*print_fn)(node->info, pinfo); - rv = (int)retval; - if (rv != LDAPU_SUCCESS) return rv; - node = node->next; - } - - return LDAPU_SUCCESS; -} - static void ldapu_list_free (LDAPUList_t *list, LDAPUListNodeFn_t free_fn) { @@ -362,44 +274,6 @@ NSAPI_PUBLIC int ldapu_propval_alloc (const char *prop, const char *val, } } -static void *ldapu_propval_copy (void *info, void *arg) -{ - LDAPUPropVal_t *propval = (LDAPUPropVal_t *)info; - LDAPUPropVal_t *copy = 0; - int rv; - - rv = ldapu_propval_alloc(propval->prop, propval->val, &copy); - - if (rv != LDAPU_SUCCESS) { - if (copy) ldapu_propval_free(copy, 0); - return 0; - } - - return copy; -} - -#define PRINT_STR(x) (x ? x : "<NULL>") - -static void * ldapu_propval_print (void *info, void *arg) -{ - LDAPUPropVal_t *propval = (LDAPUPropVal_t *)info; - LDAPUPrintInfo_t *pinfo = (LDAPUPrintInfo_t *)arg; - - if (!pinfo || !pinfo->fp) { - fprintf(stderr, "\tprop = \"%s\", \tval = \"%s\"\n", - PRINT_STR(propval->prop), - PRINT_STR(propval->val)); - } - else { - char *issuerName = (char *)pinfo->arg; - - fprintf(pinfo->fp, "%s:%s %s\n", issuerName, - propval->prop ? propval->prop : "", - propval->val ? propval->val : ""); - } - - return 0; -} static int PresentInComps (long comps_bitmask, int tag) { @@ -411,79 +285,6 @@ static int PresentInComps (long comps_bitmask, int tag) return 0; } -static void print_oid_bitmask (long bitmask) -{ - fprintf(stderr, "%lx: ", bitmask); - - if (PresentInComps(bitmask, SEC_OID_AVA_COUNTRY_NAME)) - fprintf(stderr, " C"); - if (PresentInComps(bitmask, SEC_OID_AVA_ORGANIZATION_NAME)) - fprintf(stderr, " O"); - if (PresentInComps(bitmask, SEC_OID_AVA_COMMON_NAME)) - fprintf(stderr, " CN"); - if (PresentInComps(bitmask, SEC_OID_AVA_LOCALITY)) - fprintf(stderr, " L"); - if (PresentInComps(bitmask, SEC_OID_AVA_STATE_OR_PROVINCE)) - fprintf(stderr, " ST"); - if (PresentInComps(bitmask, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME)) - fprintf(stderr, " OU"); - if (PresentInComps(bitmask, SEC_OID_PKCS9_EMAIL_ADDRESS)) - fprintf(stderr, " E"); - if (PresentInComps(bitmask, SEC_OID_RFC1274_UID)) - fprintf(stderr, " UID"); - if (PresentInComps(bitmask, SEC_OID_RFC1274_MAIL)) - fprintf(stderr, " MAIL"); - if (PresentInComps(bitmask, SEC_OID_AVA_DC)) - fprintf(stderr, " DC"); - /* check for not yet known oid */ - if (PresentInComps(bitmask, 34325)) - fprintf(stderr, " UNKNOWN"); - - fprintf(stderr, "\n"); -} - -static void *ldapu_certinfo_print (void *info, void *arg) -{ - LDAPUCertMapInfo_t *certinfo = (LDAPUCertMapInfo_t*)info; - LDAPUPrintInfo_t *pinfo = (LDAPUPrintInfo_t *)arg; - - if (!certinfo) return (void *)LDAPU_ERR_WRONG_ARGS; - - if (!pinfo || !pinfo->fp) { - fprintf(stderr, "Printing cert mapinfo: \"%s\" ...\n", - PRINT_STR(certinfo->issuerName)); - fprintf(stderr, "\tissuerDN = \"%s\"\n", - PRINT_STR(certinfo->issuerDN)); - fprintf(stderr, "\tParsed dncomps: "); - print_oid_bitmask(certinfo->dncomps); - fprintf(stderr, "\tParsed filtercomps: "); - print_oid_bitmask(certinfo->filtercomps); - - if (certinfo->propval) { - fprintf(stderr, "\tPrinting propval pairs: ...\n"); - if (certinfo->propval) - ldapu_list_print(certinfo->propval, ldapu_propval_print, pinfo); - } - else { - fprintf(stderr, "\tNo propval pairs\n"); - } - } - else { - LDAPUPrintInfo_t pinfo2; - - pinfo2.fp = pinfo->fp; - pinfo2.arg = certinfo->issuerName; - - /* Write certinfo to pinfo->fp */ - fprintf(pinfo->fp, "%s %s %s\n", LIB_DIRECTIVE, certinfo->issuerName, - certinfo->issuerDN ? certinfo->issuerDN : ""); - if (certinfo->propval) - ldapu_list_print(certinfo->propval, ldapu_propval_print, &pinfo2); - fprintf(pinfo->fp, "\n"); - } - - return (void *)LDAPU_SUCCESS; -} static int dbconf_to_certmap_err (int err) { @@ -1631,19 +1432,6 @@ done: return rv; } -/* ldapu_propval_same - returns LDAPU_SUCCESS or LDAPU_FAILED */ -static void * ldapu_propval_same (void *info, void *find_arg) -{ - /* check if info has find_arg as the issuerDN */ - const char *issuerDN = (const char *)find_arg; - const LDAPUCertMapInfo_t *certinfo = (const LDAPUCertMapInfo_t *) info; - - if (!ldapu_strcasecmp(certinfo->issuerDN, issuerDN)) - return (void *)LDAPU_SUCCESS; - else - return (void *)LDAPU_FAILED; -} - static void * ldapu_propval_free (void *propval_in, void *arg) { LDAPUPropVal_t *propval = (LDAPUPropVal_t *)propval_in; diff --git a/lib/libaccess/aclcache.cpp b/lib/libaccess/aclcache.cpp index 105888791..f814df7cf 100644 --- a/lib/libaccess/aclcache.cpp +++ b/lib/libaccess/aclcache.cpp @@ -52,6 +52,7 @@ #include <libaccess/usrcache.h> #include <libaccess/las.h> #include "aclutil.h" +#define NO_ACL_HASH_FUNCS #include "permhash.h" #include "aclcache.h" diff --git a/lib/libaccess/aclflush.cpp b/lib/libaccess/aclflush.cpp index 8e5ce7c88..a2f446181 100644 --- a/lib/libaccess/aclflush.cpp +++ b/lib/libaccess/aclflush.cpp @@ -52,7 +52,6 @@ #include <libaccess/aclglobal.h> #include <libaccess/las.h> #include "aclcache.h" -#include <libaccess/dbtlibaccess.h> extern void ACL_DatabaseDestroy(void); diff --git a/lib/libaccess/aclpriv.h b/lib/libaccess/aclpriv.h index a95b3637b..8744ef021 100644 --- a/lib/libaccess/aclpriv.h +++ b/lib/libaccess/aclpriv.h @@ -61,6 +61,7 @@ #define ACL_MIN_IDX 0 #define ACL_EXPR_STACK 1024 #define ACL_TABLE_THRESHOLD 10 +#define ACL_NO_UNPUT 1 /* unput is not used and causes compiler warnings */ typedef enum { ACL_EXPR_OP_AND, diff --git a/lib/libaccess/authdb.cpp b/lib/libaccess/authdb.cpp index da435c39f..4196c3ab1 100644 --- a/lib/libaccess/authdb.cpp +++ b/lib/libaccess/authdb.cpp @@ -47,7 +47,6 @@ #include <plhash.h> #include <netsite.h> -#include "permhash.h" #include <ldaputil/errors.h> #include <ldaputil/certmap.h> #include <ldaputil/dbconf.h> @@ -250,117 +249,6 @@ NSAPI_PUBLIC int ACL_DatabaseFind(NSErr_t *errp, const char *name, return LAS_EVAL_FAIL; } - -NSAPI_PUBLIC int ACL_ReadDbMapFile (NSErr_t *errp, const char *map_file, - int default_only) -{ - DBConfInfo_t *info; - DBConfDBInfo_t *db_info; - DBPropVal_t *propval; - PList_t plist; - int rv; - int seen_default = 0; - - if (default_only) - rv = dbconf_read_default_dbinfo(map_file, &db_info); - else - rv = dbconf_read_config_file(map_file, &info); - - if (rv != LDAPU_SUCCESS) { - nserrGenerate(errp, ACLERRFAIL, ACLERR4600, ACL_Program, 3, XP_GetAdminStr(DBT_ReadDbMapFileErrorReadingFile), map_file, ldapu_err2string(rv)); - return -1; - } - - rv = 0; - - if (!default_only) - db_info = info->firstdb; - - while(db_info) { - char *url = db_info->url; - char *dbname = db_info->dbname; - ACLDbType_t dbtype; - - /* process db_info */ - if (url) { - rv = acl_url_to_dbtype(url, &dbtype); - - if (rv < 0) { - nserrGenerate(errp, ACLERRFAIL, ACLERR4610, ACL_Program, 2, - XP_GetAdminStr(DBT_ReadDbMapFileCouldntDetermineDbtype), url); - break; - } - } - else { - nserrGenerate(errp, ACLERRFAIL, ACLERR4620, ACL_Program, 2, - XP_GetAdminStr(DBT_ReadDbMapFileMissingUrl), dbname); - rv = -1; - break; - } - - /* convert any property-value pairs in db_info into plist */ - plist = PListNew(NULL); - propval = db_info->firstprop; - - while(propval) { - if (propval->prop) { - PListInitProp(plist, 0, propval->prop, propval->val, 0); - } - else { - nserrGenerate(errp, ACLERRINVAL, ACLERR4630, ACL_Program, 2, - XP_GetAdminStr(DBT_ReadDbMapFileInvalidPropertyPair), dbname); - rv = -1; - break; - } - propval = propval->next; - } - - if (rv < 0) break; - - /* register the database */ - rv = ACL_DatabaseRegister(errp, dbtype, dbname, url, plist); - PListDestroy(plist); - - if (rv < 0) { - /* Failed to register database */ - nserrGenerate(errp, ACLERRFAIL, ACLERR4640, ACL_Program, 2, - XP_GetAdminStr(DBT_ReadDbMapFileRegisterDatabaseFailed), dbname); - break; - } - - /* If the dbname is "default", set the default_dbtype */ - if (!strcmp(dbname, DBCONF_DEFAULT_DBNAME)) { - if (!ACL_DbTypeIsEqual(errp, dbtype, ACL_DbTypeLdap)) { - nserrGenerate(errp, ACLERRINVAL, ACLERR4350, ACL_Program, 1, - XP_GetAdminStr(DBT_ReadDbMapFileDefaultDatabaseNotLdap)); - rv = -1; - break; - } - if (seen_default) { - nserrGenerate(errp, ACLERRINVAL, ACLERR4360, ACL_Program, 1, XP_GetAdminStr(DBT_ReadDbMapFileMultipleDefaultDatabases)); - rv = -1; - break; - } - seen_default = 1; - ACL_DatabaseSetDefault(errp, dbname); - } - - db_info = db_info->next; - } - - if (!seen_default) { - nserrGenerate(errp, ACLERRINVAL, ACLERR4370, ACL_Program, 1, XP_GetAdminStr(DBT_ReadDbMapFileMissingDefaultDatabase)); - rv = -1; - } - - if (default_only) - dbconf_free_dbinfo(db_info); - else - dbconf_free_confinfo(info); - - return rv; -} - void ACL_DatabaseDestroy(void) { diff --git a/lib/libaccess/oneeval.cpp b/lib/libaccess/oneeval.cpp index 8056e0ec3..ed29ee47a 100644 --- a/lib/libaccess/oneeval.cpp +++ b/lib/libaccess/oneeval.cpp @@ -70,6 +70,7 @@ #include "aclutil.h" #include "aclcache.h" #include "oneeval.h" +#define NO_ACL_HASH_FUNCS #include "permhash.h" static ACLDispatchVector_t __nsacl_vector = { diff --git a/lib/libaccess/permhash.h b/lib/libaccess/permhash.h index f76ab4c63..9446fb552 100644 --- a/lib/libaccess/permhash.h +++ b/lib/libaccess/permhash.h @@ -80,13 +80,7 @@ static PLHashAllocOps ACLPermAllocOps = { ACL_PermFreeEntry }; -static int -PR_StringFree(PLHashEntry *he, int i, void *arg) -{ - PERM_FREE(he->key); - return 0; -} - +#ifndef NO_ACL_HASH_FUNCS static PLHashNumber PR_HashCaseString(const void *key) { @@ -111,6 +105,7 @@ PR_CompareCaseStrings(const void *v1, const void *v2) return (strcasecmp(s1, s2) == 0); #endif } - +#endif /* NO_ACL_HASH_FUNCS */ + #endif /* _PERMHASH_H */ diff --git a/lib/libaccess/register.cpp b/lib/libaccess/register.cpp index 09d918fcd..3f2acc5eb 100644 --- a/lib/libaccess/register.cpp +++ b/lib/libaccess/register.cpp @@ -56,7 +56,6 @@ #include <libaccess/aclproto.h> #include <libaccess/aclglobal.h> #include "aclcache.h" -#include <libaccess/dbtlibaccess.h> #include <libaccess/aclerror.h> /* This is to force aclspace.o into ns-httpd30.dll */
0
05934307c9381bae9ad29288ed63290fcd09e0c8
389ds/389-ds-base
Issue 6753 - Port ticket test 47619 Description: Porting ticket 47619 test to dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py. Relates: #6753 Author: Lenka Doudova Reviewer: Simon Pichugin
commit 05934307c9381bae9ad29288ed63290fcd09e0c8 Author: Lenka Doudova <[email protected]> Date: Wed May 14 10:57:12 2025 +0200 Issue 6753 - Port ticket test 47619 Description: Porting ticket 47619 test to dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py. Relates: #6753 Author: Lenka Doudova Reviewer: Simon Pichugin diff --git a/dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py b/dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py index 1e9ee27c7..c0997d1d2 100644 --- a/dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py +++ b/dirsrvtests/tests/suites/retrocl/retrocl_indexing_test.py @@ -9,13 +9,27 @@ import logging import pytest import os +import ldap from lib389._constants import RETROCL_SUFFIX, DEFAULT_SUFFIX from lib389.topologies import topology_st as topo +from lib389.topologies import topology_m1 from lib389.plugins import RetroChangelogPlugin from lib389.idm.user import UserAccounts from lib389._mapped_object import DSLdapObjects +from lib389.properties import TASK_WAIT, INDEX_TYPE +from lib389.index import Indexes + + log = logging.getLogger(__name__) +TEST_REPL_DN = "cn=test_repl,{}".format(DEFAULT_SUFFIX) +ENTRY_DN = "cn=test_entry,{}".format(DEFAULT_SUFFIX) + +OTHER_NAME = 'other_entry' +MAX_OTHERS = 100 + +ATTRIBUTES = ['street', 'countryName', 'description', 'postalAddress', 'postalCode', 'title', 'l', 'roomNumber'] + def test_indexing_is_online(topo): """Test that the changenmumber index is online right after enabling the plugin @@ -69,6 +83,81 @@ def test_indexing_is_online(topo): assert not topo.standalone.searchAccessLog('Partially Unindexed Filter') +def test_reindexing_retrochangelog(topology_m1): + """ Test that the retro changelog can be successfully reindexed + + :id: 26d8df59-0886-4098-8d2c-b9337accc908 + :setup: Supplier instance + :steps: + 1. Enable retro changelog and restart instance + 2. Create test entries + 3. Create index + 4. Reindex retro changelog + 5. Verify indexed search + 6. Clean up test entries + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + 5. Success + 6. Success + """ + + log.info('Enable retro changelog and restart instance') + retrocl = RetroChangelogPlugin(topology_m1.ms["supplier1"]) + retrocl.enable() + topology_m1.ms["supplier1"].restart() + + log.info('Creating test entries') + users = UserAccounts(topology_m1.ms["supplier1"], DEFAULT_SUFFIX) + for count in range(MAX_OTHERS): + name = "{}{}".format(OTHER_NAME, count) + users.create(properties={ + 'sn': name, + 'cn': name, + 'uid': name, + 'uidNumber': '1{}'.format(count), + 'gidNumber': '11{}'.format(count), + 'homeDirectory': '/home/{}'.format(name) + }) + + log.info('Test entries created') + + try: + log.info('Verify number of created entries') + check_entries = users.list() + assert len(check_entries) == MAX_OTHERS + + log.info('Create index') + indexes = Indexes(topology_m1.ms["supplier1"]) + for attr in ATTRIBUTES: + indexes.create(properties={ + 'cn': attr, + 'nsSystemIndex': 'false', + 'nsIndexType': 'eq' + }) + topology_m1.ms["supplier1"].restart() + + log.info('Reindex retro changelog') + args = {TASK_WAIT: True} + for attr in ATTRIBUTES: + rc = topology_m1.ms["supplier1"].tasks.reindex(suffix=RETROCL_SUFFIX, attrname=attr, args=args) + log.info('Verify reindexing task was successful for attribute {}'.format(attr)) + assert rc == 0 + + log.info('Check reindexed search') + for attr in ATTRIBUTES: + ents = topology_m1.ms["supplier1"].search_s(RETROCL_SUFFIX, ldap.SCOPE_SUBTREE, "({}=hello)".format(attr), + escapehatch='i am sure') + assert len(ents) == 0 + finally: + log.info('Clean up the test entries') + entries = users.list() + for entry in entries: + entry.delete() + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode diff --git a/dirsrvtests/tests/tickets/ticket47619_test.py b/dirsrvtests/tests/tickets/ticket47619_test.py deleted file mode 100644 index d95d86514..000000000 --- a/dirsrvtests/tests/tickets/ticket47619_test.py +++ /dev/null @@ -1,97 +0,0 @@ -# --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2016 Red Hat, Inc. -# All rights reserved. -# -# License: GPL (version 3 or any later version). -# See LICENSE for details. -# --- END COPYRIGHT BLOCK --- -# -''' -Created on Nov 7, 2013 - -@author: tbordaz -''' -import logging -import time - -import ldap -import pytest -from lib389 import Entry -from lib389._constants import * -from lib389.properties import * -from lib389.topologies import topology_m1c1 - -pytestmark = pytest.mark.tier2 - -logging.getLogger(__name__).setLevel(logging.DEBUG) -log = logging.getLogger(__name__) - -TEST_REPL_DN = "cn=test_repl, %s" % SUFFIX -ENTRY_DN = "cn=test_entry, %s" % SUFFIX - -OTHER_NAME = 'other_entry' -MAX_OTHERS = 100 - -ATTRIBUTES = ['street', 'countryName', 'description', 'postalAddress', 'postalCode', 'title', 'l', 'roomNumber'] - - -def test_ticket47619_init(topology_m1c1): - """ - Initialize the test environment - """ - topology_m1c1.ms["supplier1"].plugins.enable(name=PLUGIN_RETRO_CHANGELOG) - # topology_m1c1.ms["supplier1"].plugins.enable(name=PLUGIN_MEMBER_OF) - # topology_m1c1.ms["supplier1"].plugins.enable(name=PLUGIN_REFER_INTEGRITY) - topology_m1c1.ms["supplier1"].stop(timeout=10) - topology_m1c1.ms["supplier1"].start(timeout=10) - - topology_m1c1.ms["supplier1"].log.info("test_ticket47619_init topology_m1c1 %r" % (topology_m1c1)) - # the test case will check if a warning message is logged in the - # error log of the supplier - topology_m1c1.ms["supplier1"].errorlog_file = open(topology_m1c1.ms["supplier1"].errlog, "r") - - # add dummy entries - for cpt in range(MAX_OTHERS): - name = "%s%d" % (OTHER_NAME, cpt) - topology_m1c1.ms["supplier1"].add_s(Entry(("cn=%s,%s" % (name, SUFFIX), { - 'objectclass': "top person".split(), - 'sn': name, - 'cn': name}))) - - topology_m1c1.ms["supplier1"].log.info( - "test_ticket47619_init: %d entries ADDed %s[0..%d]" % (MAX_OTHERS, OTHER_NAME, MAX_OTHERS - 1)) - - # Check the number of entries in the retro changelog - time.sleep(2) - ents = topology_m1c1.ms["supplier1"].search_s(RETROCL_SUFFIX, ldap.SCOPE_ONELEVEL, "(objectclass=*)") - assert len(ents) == MAX_OTHERS - - -def test_ticket47619_create_index(topology_m1c1): - args = {INDEX_TYPE: 'eq'} - for attr in ATTRIBUTES: - topology_m1c1.ms["supplier1"].index.create(suffix=RETROCL_SUFFIX, attr=attr, args=args) - topology_m1c1.ms["supplier1"].restart(timeout=10) - - -def test_ticket47619_reindex(topology_m1c1): - ''' - Reindex all the attributes in ATTRIBUTES - ''' - args = {TASK_WAIT: True} - for attr in ATTRIBUTES: - rc = topology_m1c1.ms["supplier1"].tasks.reindex(suffix=RETROCL_SUFFIX, attrname=attr, args=args) - assert rc == 0 - - -def test_ticket47619_check_indexed_search(topology_m1c1): - for attr in ATTRIBUTES: - ents = topology_m1c1.ms["supplier1"].search_s(RETROCL_SUFFIX, ldap.SCOPE_SUBTREE, "(%s=hello)" % attr) - assert len(ents) == 0 - - -if __name__ == '__main__': - # Run isolated - # -s for DEBUG mode - CURRENT_FILE = os.path.realpath(__file__) - pytest.main("-s %s" % CURRENT_FILE)
0
7f899a45f6d963a75df62481a9730b912ae325d3
389ds/389-ds-base
Ticket 3 - lib389 - config test Bug Description: python 3 suppor for config test Fix Description: Fix python 3 support for config test, correct a small issue in removal, and improve some logging of large values https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!)
commit 7f899a45f6d963a75df62481a9730b912ae325d3 Author: William Brown <[email protected]> Date: Tue Nov 7 16:15:31 2017 +1000 Ticket 3 - lib389 - config test Bug Description: python 3 suppor for config test Fix Description: Fix python 3 support for config test, correct a small issue in removal, and improve some logging of large values https://pagure.io/lib389/issue/3 Author: wibrown Review by: spichugi (Thanks!) diff --git a/dirsrvtests/tests/suites/config/config_test.py b/dirsrvtests/tests/suites/config/config_test.py index 6ed2a2f12..99871378a 100644 --- a/dirsrvtests/tests/suites/config/config_test.py +++ b/dirsrvtests/tests/suites/config/config_test.py @@ -14,6 +14,10 @@ from lib389.topologies import topology_m2 from lib389._constants import DN_CONFIG, DEFAULT_SUFFIX +from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES + +from lib389.config import LDBMConfig + USER_DN = 'uid=test_user,%s' % DEFAULT_SUFFIX logging.getLogger(__name__).setLevel(logging.INFO) @@ -32,37 +36,7 @@ def big_file(): return TEMP_BIG_FILE [email protected] -def test_user(topology_m2): - """Add and remove test user""" - - try: - topology_m2.ms["master1"].add_s(Entry((USER_DN, { - 'uid': 'test_user', - 'givenName': 'test_user', - 'objectclass': ['top', 'person', - 'organizationalPerson', - 'inetorgperson'], - 'cn': 'test_user', - 'sn': 'test_user'}))) - time.sleep(1) - except ldap.LDAPError as e: - log.fatal('Failed to add user (%s): error (%s)' % (USER_DN, - e.message['desc'])) - raise - - def fin(): - try: - topology_m2.ms["master1"].delete_s(USER_DN) - time.sleep(1) - except ldap.LDAPError as e: - log.fatal('Failed to delete user (%s): error (%s)' % ( - USER_DN, - e.message['desc'])) - raise - - -def test_maxbersize_repl(topology_m2, test_user, big_file): +def test_maxbersize_repl(topology_m2, big_file): """maxbersize is ignored in the replicated operations. :id: ad57de60-7d56-4323-bbca-5556e5cdb126 @@ -80,64 +54,38 @@ def test_maxbersize_repl(topology_m2, test_user, big_file): 4. The big value is successfully replicated to master2 """ + users_m1 = UserAccounts(topology_m2.ms["master1"], DEFAULT_SUFFIX) + users_m2 = UserAccounts(topology_m2.ms["master2"], DEFAULT_SUFFIX) + + user_m1 = users_m1.create(properties=TEST_USER_PROPERTIES) + time.sleep(2) + user_m2 = users_m2.get(dn=user_m1.dn) + log.info("Set nsslapd-maxbersize: 20K to master2") - try: - topology_m2.ms["master2"].modify_s("cn=config", [(ldap.MOD_REPLACE, - 'nsslapd-maxbersize', '20480')]) - except ldap.LDAPError as e: - log.error('Failed to set nsslapd-maxbersize == 20480: error ' + - e.message['desc']) - raise + topology_m2.ms["master2"].config.set('nsslapd-maxbersize', '20480') - topology_m2.ms["master2"].restart(20) + topology_m2.ms["master2"].restart() log.info('Try to add attribute with a big value to master2 - expect to FAIL') with pytest.raises(ldap.SERVER_DOWN): - topology_m2.ms["master2"].modify_s(USER_DN, [(ldap.MOD_REPLACE, - 'jpegphoto', big_file)]) + user_m2.add('jpegphoto', big_file) - topology_m2.ms["master2"].restart(20) - topology_m2.ms["master1"].restart(20) + topology_m2.ms["master2"].restart() + topology_m2.ms["master1"].restart() log.info('Try to add attribute with a big value to master1 - expect to PASS') - try: - topology_m2.ms["master1"].modify_s(USER_DN, [(ldap.MOD_REPLACE, - 'jpegphoto', big_file)]) - except ldap.SERVER_DOWN as e: - log.fatal('Failed to add a big attribute, error: ' + e.message['desc']) - raise + user_m1.add('jpegphoto', big_file) - time.sleep(1) + time.sleep(2) log.info('Check if a big value was successfully added to master1') - try: - entries = topology_m2.ms["master1"].search_s(USER_DN, ldap.SCOPE_BASE, - '(cn=*)', - ['jpegphoto']) - assert entries[0].data['jpegphoto'] - except ldap.LDAPError as e: - log.fatal('Search failed, error: ' + e.message['desc']) - raise + + photo_m1 = user_m1.get_attr_vals('jpegphoto') log.info('Check if a big value was successfully replicated to master2') - try: - entries = topology_m2.ms["master2"].search_s(USER_DN, ldap.SCOPE_BASE, - '(cn=*)', - ['jpegphoto']) - assert entries[0].data['jpegphoto'] - except ldap.LDAPError as e: - log.fatal('Search failed, error: ' + e.message['desc']) - raise - - log.info("Set nsslapd-maxbersize: 2097152 (default) to master2") - try: - topology_m2.ms["master2"].modify_s("cn=config", [(ldap.MOD_REPLACE, - 'nsslapd-maxbersize', '2097152')]) - except ldap.LDAPError as e: - log.error('Failed to set nsslapd-maxbersize == 2097152 error ' + - e.message['desc']) - raise + photo_m2 = user_m2.get_attr_vals('jpegphoto') + assert photo_m2 == photo_m1 def test_config_listen_backport_size(topology_m2): """Check that nsslapd-listen-backlog-size acted as expected @@ -158,46 +106,16 @@ def test_config_listen_backport_size(topology_m2): 5. nsslapd-listen-backlog-size should be successfully set """ - try: - entry = topology_m2.ms["master1"].search_s(DN_CONFIG, ldap.SCOPE_BASE, 'objectclass=top', - ['nsslapd-listen-backlog-size']) - default_val = entry[0].data['nsslapd-listen-backlog-size'][0] - assert default_val, 'Failed to get nsslapd-listen-backlog-size from config' - except ldap.LDAPError as e: - log.fatal('Failed to search config, error: ' + e.message('desc')) - raise - - try: - topology_m2.ms["master1"].modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-listen-backlog-size', - '256')]) - except ldap.LDAPError as e: - log.fatal('Failed to modify config, error: ' + e.message('desc')) - raise - - try: - topology_m2.ms["master1"].modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-listen-backlog-size', - '-1')]) - except ldap.LDAPError as e: - log.fatal('Failed to modify config(negative value), error: ' + - e.message('desc')) - raise + default_val = topology_m2.ms["master1"].config.get_attr_val_bytes('nsslapd-listen-backlog-size') + + topology_m2.ms["master1"].config.replace('nsslapd-listen-backlog-size', '256') + + topology_m2.ms["master1"].config.replace('nsslapd-listen-backlog-size', '-1') with pytest.raises(ldap.LDAPError): - topology_m2.ms["master1"].modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-listen-backlog-size', - 'ZZ')]) - log.fatal('Invalid value was successfully added') + topology_m2.ms["master1"].config.replace('nsslapd-listen-backlog-size', 'ZZ') - # Cleanup - undo what we've done - try: - topology_m2.ms["master1"].modify_s(DN_CONFIG, [(ldap.MOD_REPLACE, - 'nsslapd-listen-backlog-size', - default_val)]) - except ldap.LDAPError as e: - log.fatal('Failed to reset config, error: ' + e.message('desc')) - raise + topology_m2.ms["master1"].config.replace('nsslapd-listen-backlog-size', default_val) def test_config_deadlock_policy(topology_m2): @@ -220,47 +138,25 @@ def test_config_deadlock_policy(topology_m2): 5. nsslapd-db-deadlock-policy should be successfully set """ - LDBM_DN = 'cn=config,cn=ldbm database,cn=plugins,cn=config' - default_val = '9' + default_val = b'9' + + ldbmconfig = LDBMConfig(topology_m2.ms["master1"]) + + deadlock_policy = ldbmconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + assert deadlock_policy == default_val - try: - entry = topology_m2.ms["master1"].search_s(LDBM_DN, ldap.SCOPE_BASE, 'objectclass=top', - ['nsslapd-db-deadlock-policy']) - val = entry[0].data['nsslapd-db-deadlock-policy'][0] - assert val, 'Failed to get nsslapd-db-deadlock-policy from config' - assert val == default_val, 'The wrong default value was present' - except ldap.LDAPError as e: - log.fatal('Failed to search config, error: ' + e.message('desc')) - raise # Try a range of valid values for val in ('0', '5', '9'): - try: - topology_m2.ms["master1"].modify_s(LDBM_DN, [(ldap.MOD_REPLACE, - 'nsslapd-db-deadlock-policy', - val)]) - except ldap.LDAPError as e: - log.fatal('Failed to modify config: nsslapd-db-deadlock-policy to (%s), error: %s' % - (val, e.message('desc'))) - raise + ldbmconfig.replace('nsslapd-db-deadlock-policy', val) # Try a range of invalid values for val in ('-1', '10'): with pytest.raises(ldap.LDAPError): - topology_m2.ms["master1"].modify_s(LDBM_DN, [(ldap.MOD_REPLACE, - 'nsslapd-db-deadlock-policy', - val)]) - log.fatal('Able to add invalid value to nsslapd-db-deadlock-policy(%s)' % (val)) + ldbmconfig.replace('nsslapd-db-deadlock-policy', val) # Cleanup - undo what we've done - try: - topology_m2.ms["master1"].modify_s(LDBM_DN, [(ldap.MOD_REPLACE, - 'nsslapd-db-deadlock-policy', - default_val)]) - except ldap.LDAPError as e: - log.fatal('Failed to reset nsslapd-db-deadlock-policy to the default value(%s), error: %s' % - (default_val, e.message('desc'))) - raise + ldbmconfig.replace('nsslapd-db-deadlock-policy', deadlock_policy) if __name__ == '__main__': diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index b08c09b43..8a49df4fe 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -1274,16 +1274,20 @@ class DirSrv(SimpleLDAPObject, object): # TODO: use the status call instead!!!! pid = pid_from_file(self.ds_paths.pid_file) if pid is None: + self.log.debug("No pidfile found for %s" % self.serverid) # No pidfile yet ... self.state = DIRSRV_STATE_OFFLINE return False if pid == 0: + self.log.debug("Pid of 0 not valid for %s" % self.serverid) self.state = DIRSRV_STATE_OFFLINE raise ValueError # Wait if not pid_exists(pid): + self.log.debug("Pid of %s is not running for %s" % (pid, self.serverid)) self.state = DIRSRV_STATE_OFFLINE return False + self.log.debug("Pid of %s for %s and running" % (pid, self.serverid)) return True def restart(self, timeout=120, post_open=True): diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 40d2aae94..4e5bc727a 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -295,7 +295,10 @@ class DSLdapObject(DSLogging): :raises: ValueError - if instance is not online """ - self._log.debug("%s set(%r, %r)" % (self._dn, key, value)) + if value is None or len(value) < 512: + self._log.debug("%s set(%r, %r)" % (self._dn, key, value)) + else: + self._log.debug("%s set(%r, value too large)" % (self._dn, key)) if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot set properties on instance that is not ONLINE.") @@ -804,6 +807,7 @@ class DSLdapObjects(DSLogging): # This will yield and & filter for objectClass with as many terms as needed. filterstr = self._get_objectclass_filter() self._log.debug('_gen_dn filter = %s' % filterstr) + self._log.debug('_gen_dn dn = %s' % dn) return self._instance.search_ext_s( base=dn, scope=ldap.SCOPE_BASE, diff --git a/src/lib389/lib389/config.py b/src/lib389/lib389/config.py index 0a7539b1d..566b75419 100644 --- a/src/lib389/lib389/config.py +++ b/src/lib389/lib389/config.py @@ -350,4 +350,25 @@ class CertmapLegacy(object): f.write(output) +class LDBMConfig(DSLdapObject): + """ + Manage "cn=config,cn=ldbm database,cn=plugins,cn=config" including: + - Performance related tunings + - DB backend settings + + :param instance: An instance + :type instance: lib389.DirSrv + :param batch: Not implemented + :type batch: bool + """ + + def __init__(self, conn, batch=False): + super(LDBMConfig, self).__init__(instance=conn, batch=batch) + self._dn = DN_CONFIG_LDBM + config_compare_exclude = [] + self._rdn_attribute = 'cn' + self._lint_functions = [] + self._protected = True + + diff --git a/src/lib389/lib389/instance/remove.py b/src/lib389/lib389/instance/remove.py index 9ce8505bf..fce1d2d4f 100644 --- a/src/lib389/lib389/instance/remove.py +++ b/src/lib389/lib389/instance/remove.py @@ -26,11 +26,12 @@ def remove_ds_instance(dirsrv): remove_paths['db_dir'] = dirsrv.ds_paths.db_dir ### WARNING: The changelogdb isn't removed. we assume it's in: # db_dir ../changelogdb. So remove that too! - remove_paths['changelogdb_dir'] = os.path.join(dirsrv.ds_paths.db_dir, '../changelogdb') + # abspath will resolve the ".." down. + remove_paths['changelogdb_dir'] = os.path.abspath(os.path.join(dirsrv.ds_paths.db_dir, '../changelogdb')) remove_paths['ldif_dir'] = dirsrv.ds_paths.ldif_dir remove_paths['lock_dir'] = dirsrv.ds_paths.lock_dir remove_paths['log_dir'] = dirsrv.ds_paths.log_dir - remove_paths['run_dir'] = dirsrv.ds_paths.run_dir + # remove_paths['run_dir'] = dirsrv.ds_paths.run_dir marker_path = "%s/sysconfig/dirsrv-%s" % (dirsrv.ds_paths.sysconf_dir, dirsrv.serverid) @@ -44,9 +45,8 @@ def remove_ds_instance(dirsrv): # for path in ('backup_dir', 'cert_dir', 'config_dir', 'db_dir', # 'ldif_dir', 'lock_dir', 'log_dir', 'run_dir'): for path_k in remove_paths: - if os.path.exists(remove_paths[path_k]): - _log.debug("Removing %s" % remove_paths[path_k]) - shutil.rmtree(remove_paths[path_k]) + _log.debug("Removing %s" % remove_paths[path_k]) + shutil.rmtree(remove_paths[path_k], ignore_errors=True) # Finally remove the sysconfig marker. os.remove(marker_path)
0
f9db3ac14855eb07e49f2f5797cbb7d338bb614b
389ds/389-ds-base
Fix various compiler warnings 1) Make sure we use "const" consistently 2) Make sure we use "unsigned char" consistently for some reason (unsigned char)*p did not compare to '\xHH' literals unless the literal was also cast to (unsigned char) 3) added some missing function prototypes 4) removed some unused variables/functions, or commented out for use when debugging 5) various other compiler warnings With all of these, the code compiles cleanly on RHEL5 x86_64 using gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44) and CFLAGS="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic" The only warning now is the spurious message about %llu or %lld having the wrong format argument. Reviewed by: nhosoi (Thanks!)
commit f9db3ac14855eb07e49f2f5797cbb7d338bb614b Author: Rich Megginson <[email protected]> Date: Tue May 19 13:17:11 2009 -0600 Fix various compiler warnings 1) Make sure we use "const" consistently 2) Make sure we use "unsigned char" consistently for some reason (unsigned char)*p did not compare to '\xHH' literals unless the literal was also cast to (unsigned char) 3) added some missing function prototypes 4) removed some unused variables/functions, or commented out for use when debugging 5) various other compiler warnings With all of these, the code compiles cleanly on RHEL5 x86_64 using gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44) and CFLAGS="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic" The only warning now is the spurious message about %llu or %lld having the wrong format argument. Reviewed by: nhosoi (Thanks!) diff --git a/ldap/servers/plugins/acl/acllas.c b/ldap/servers/plugins/acl/acllas.c index e79562a9d..baa756db4 100644 --- a/ldap/servers/plugins/acl/acllas.c +++ b/ldap/servers/plugins/acl/acllas.c @@ -1130,7 +1130,7 @@ struct userdnattr_info { char *attr; int result; char *clientdn; - Acl_PBlock *aclpb + Acl_PBlock *aclpb; }; #define ACLLAS_MAX_LEVELS 10 int diff --git a/ldap/servers/plugins/syntaxes/cis.c b/ldap/servers/plugins/syntaxes/cis.c index f20ae5eb6..4f1d9d718 100644 --- a/ldap/servers/plugins/syntaxes/cis.c +++ b/ldap/servers/plugins/syntaxes/cis.c @@ -730,7 +730,7 @@ static int postal_validate( if (*p == '\\') { p++; /* ensure that we're not at the end of the value */ - if ((p > end) || (strncmp(p, "24", 2) != 0) && (strncasecmp(p, "5C", 2) != 0)) { + if ((p > end) || ((strncmp(p, "24", 2) != 0) && (strncasecmp(p, "5C", 2) != 0))) { rc = 1; goto exit; } else { @@ -776,7 +776,7 @@ static int oid_validate( { int rc = 0; /* assume the value is valid */ const char *p = NULL; - char *end = NULL; + const char *end = NULL; /* Per RFC4512: * diff --git a/ldap/servers/plugins/syntaxes/dn.c b/ldap/servers/plugins/syntaxes/dn.c index 80a3f8bfa..ab6b254dc 100644 --- a/ldap/servers/plugins/syntaxes/dn.c +++ b/ldap/servers/plugins/syntaxes/dn.c @@ -58,7 +58,7 @@ static int dn_assertion2keys_ava( Slapi_PBlock *pb, Slapi_Value *val, static int dn_assertion2keys_sub( Slapi_PBlock *pb, char *initial, char **any, char *final, Slapi_Value ***ivals ); static int dn_validate( struct berval *val ); -static int rdn_validate( char *begin, char *end, char **last ); +static int rdn_validate( const char *begin, const char *end, const char **last ); /* the first name is the official one from RFC 2252 */ static char *names[] = { "DN", DN_SYNTAX_OID, 0 }; @@ -156,9 +156,9 @@ static int dn_validate( struct berval *val ) */ if (val->bv_len > 0) { int strict = 0; - char *p = val->bv_val; - char *end = &(val->bv_val[val->bv_len - 1]); - char *last = NULL; + const char *p = val->bv_val; + const char *end = &(val->bv_val[val->bv_len - 1]); + const char *last = NULL; /* Check if we should be performing strict validation. */ strict = config_get_dn_validate_strict(); @@ -168,7 +168,7 @@ static int dn_validate( struct berval *val ) * stored in the backend unmodified. */ val_copy = PL_strndup(val->bv_val, val->bv_len); p = val_copy; - end = slapi_dn_normalize_to_end(p, NULL) - 1; + end = slapi_dn_normalize_to_end(val_copy, NULL) - 1; } /* Validate one RDN at a time in a loop. */ @@ -212,12 +212,12 @@ exit: * will be set in the "last parameter. This will be the end of the RDN * in the valid case, and the illegal character in the invalid case. */ -static int rdn_validate( char *begin, char *end, char **last ) +static int rdn_validate( const char *begin, const char *end, const char **last ) { int rc = 0; /* Assume RDN is valid */ int numericform = 0; char *separator = NULL; - char *p = begin; + const char *p = begin; /* Find the '=', then use the helpers for descr and numericoid */ if ((separator = PL_strnchr(p, '=', end - begin + 1)) == NULL) { @@ -228,13 +228,13 @@ static int rdn_validate( char *begin, char *end, char **last ) /* Process an attribute type. The 'descr' * form must start with a 'leadkeychar'. */ if (IS_LEADKEYCHAR(*p)) { - if (rc = keystring_validate(p, separator - 1)) { + if ((rc = keystring_validate(p, separator - 1))) { goto exit; } /* See if the 'numericoid' form is being used */ } else if (isdigit(*p)) { numericform = 1; - if (rc = numericoid_validate(p, separator - 1)) { + if ((rc = numericoid_validate(p, separator - 1))) { goto exit; } } else { diff --git a/ldap/servers/plugins/syntaxes/phonetic.c b/ldap/servers/plugins/syntaxes/phonetic.c index f8f8e023c..dd9e83042 100644 --- a/ldap/servers/plugins/syntaxes/phonetic.c +++ b/ldap/servers/plugins/syntaxes/phonetic.c @@ -249,9 +249,9 @@ static char vsvfn[26] = { char * phonetic( char *Word ) { - unsigned char *n, *n_start, *n_end; /* pointers to string */ + unsigned char *n_start, *n, *n_end; /* pointers to string */ char *metaph_end; /* pointers to metaph */ - char ntrans[42]; /* word with uppercase letters */ + unsigned char ntrans[42]; /* word with uppercase letters */ int KSflag; /* state flag for X -> KS */ char buf[MAXPHONEMELEN + 2]; char *Metaph; @@ -268,7 +268,7 @@ phonetic( char *Word ) } ++Word; } else { - auto const size_t len = LDAP_UTF8COPY(n, Word); + auto const size_t len = LDAP_UTF8COPY((char *)n, Word); n += len; Word += len; } } diff --git a/ldap/servers/plugins/syntaxes/syntax.h b/ldap/servers/plugins/syntaxes/syntax.h index b9a013700..e673718f2 100644 --- a/ldap/servers/plugins/syntaxes/syntax.h +++ b/ldap/servers/plugins/syntaxes/syntax.h @@ -75,13 +75,13 @@ #define IS_LDIGIT(c) ( (c != '0') && isdigit(c) ) #define IS_SHARP(c) ( (c == '#') ) #define IS_ESC(c) ( (c == '\\') ) -#define IS_UTF0(c) ( (c >= '\x80') && (c <= '\xBF') ) -#define IS_UTF1(c) ( !(c & 128) ) +#define IS_UTF0(c) ( ((unsigned char)(c) >= (unsigned char)'\x80') && ((unsigned char)(c) <= (unsigned char)'\xBF') ) +#define IS_UTF1(c) ( !((unsigned char)(c) & 128) ) /* These are only checking the first byte of the multibyte character. They * do not verify that the entire multibyte character is correct. */ -#define IS_UTF2(c) ( (c >= '\xC2') && (c <= '\xDF') ) -#define IS_UTF3(c) ( (c >= '\xE0') && (c <= '\xEF') ) -#define IS_UTF4(c) ( (c >= '\xF0') && (c <= '\xF4') ) +#define IS_UTF2(c) ( ((unsigned char)(c) >= (unsigned char)'\xC2') && ((unsigned char)(c) <= (unsigned char)'\xDF') ) +#define IS_UTF3(c) ( ((unsigned char)(c) >= (unsigned char)'\xE0') && ((unsigned char)(c) <= (unsigned char)'\xEF') ) +#define IS_UTF4(c) ( ((unsigned char)(c) >= (unsigned char)'\xF0') && ((unsigned char)(c) <= (unsigned char)'\xF4') ) #define IS_UTFMB(c) ( IS_UTF2(c) || IS_UTF3(c) || IS_UTF4(c) ) #define IS_UTF8(c) ( IS_UTF1(c) || IS_UTFMB(c) ) @@ -119,9 +119,9 @@ char *next_word( char *s ); char *phonetic( char *s ); /* Validation helper functions */ -int keystring_validate( char *begin, char *end ); -int numericoid_validate( char *begin, char *end ); -int utf8char_validate( char *begin, char *end, char **last ); -int utf8string_validate( char *begin, char *end, char **last ); +int keystring_validate( const char *begin, const char *end ); +int numericoid_validate( const char *begin, const char *end ); +int utf8char_validate( const char *begin, const char *end, const char **last ); +int utf8string_validate( const char *begin, const char *end, const char **last ); #endif diff --git a/ldap/servers/plugins/syntaxes/validate.c b/ldap/servers/plugins/syntaxes/validate.c index 8367e0839..a34830cd0 100644 --- a/ldap/servers/plugins/syntaxes/validate.c +++ b/ldap/servers/plugins/syntaxes/validate.c @@ -52,8 +52,8 @@ * Returns non-zero if the value is not a valide 'keystring'. */ int keystring_validate( - char *begin, - char *end + const char *begin, + const char *end ) { int rc = 0; /* assume the value is valid */ @@ -90,13 +90,13 @@ exit: * Returns non-zero if the value is not a valide 'numericoid'. */ int numericoid_validate( - char *begin, - char *end + const char *begin, + const char *end ) { int rc = 0; /* assume the value is valid */ int found_separator = 0; - char *p = NULL; + const char *p = NULL; if ((begin == NULL) || (end == NULL)) { rc = 1; @@ -181,13 +181,13 @@ exit: * * Returns 0 if it is valid and non-zero otherwise. */ int utf8char_validate( - char *begin, - char *end, - char **last + const char *begin, + const char *end, + const char **last ) { int rc = 0; /* Assume char is valid */ - char *p = begin; + const char *p = begin; if ((begin == NULL) || (end == NULL)) { rc = 1; @@ -233,14 +233,14 @@ int utf8char_validate( if (*p == '\xE0') { /* The next byte must be %xA0-BF. */ p++; - if ((*p < '\xA0') || (*p > '\xBF')) { + if (((unsigned char)*p < (unsigned char)'\xA0') || ((unsigned char)*p > (unsigned char)'\xBF')) { rc = 1; goto exit; } } else if (*p == '\xED') { /* The next byte must be %x80-9F. */ p++; - if ((*p < '\x80') || (*p > '\x9F')) { + if (((unsigned char)*p < (unsigned char)'\x80') || ((unsigned char)*p > (unsigned char)'\x9F')) { rc = 1; goto exit; } @@ -270,13 +270,13 @@ int utf8char_validate( * the second byte. */ if (*p == '\xF0') { /* The next byte must be %x90-BF. */ - if ((*p < '\x90') || (*p > '\xBF')) { + if (((unsigned char)*p < (unsigned char)'\x90') || ((unsigned char)*p > (unsigned char)'\xBF')) { rc = 1; goto exit; } } else if (*p == '\xF4') { /* The next byte must be %x80-BF. */ - if ((*p < '\x80') || (*p > '\xBF')) { + if (((unsigned char)*p < (unsigned char)'\x80') || ((unsigned char)*p > (unsigned char)'\xBF')) { rc = 1; goto exit; } @@ -307,7 +307,7 @@ int utf8char_validate( exit: if (last) { - *last = p; + *last = (const char *)p; } return(rc); } @@ -321,13 +321,13 @@ exit: * * Returns 0 if it is valid and non-zero otherwise. */ int utf8string_validate( - char *begin, - char *end, - char **last + const char *begin, + const char *end, + const char **last ) { int rc = 0; /* Assume string is valid */ - char *p = NULL; + const char *p = NULL; if ((begin == NULL) || (end == NULL)) { rc = 1; diff --git a/ldap/servers/plugins/syntaxes/validate_task.c b/ldap/servers/plugins/syntaxes/validate_task.c index d469ccd61..38c35218d 100644 --- a/ldap/servers/plugins/syntaxes/validate_task.c +++ b/ldap/servers/plugins/syntaxes/validate_task.c @@ -49,8 +49,6 @@ /* * Globals */ -static Slapi_PluginDesc pdesc = { "syntax-validate-task", PLUGIN_MAGIC_VENDOR_STR, - PRODUCTTEXT, "syntax validation task plugin" }; static void* _PluginID = NULL; diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 8c13a9b6c..1155c8c71 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -124,12 +124,6 @@ static int config_set_onoff( const char *attrname, char *value, static int config_set_schemareplace ( const char *attrname, char *value, char *errorbuf, int apply ); -static int -isIntegralType(ConfigVarType type) -{ - return type == CONFIG_INT || type == CONFIG_LONG || type == CONFIG_ON_OFF; -} - static int isInt(ConfigVarType type) { diff --git a/ldap/servers/slapd/modify.c b/ldap/servers/slapd/modify.c index 09ccd424d..d90d2b49e 100644 --- a/ldap/servers/slapd/modify.c +++ b/ldap/servers/slapd/modify.c @@ -438,7 +438,7 @@ void slapi_modify_internal_set_pb (Slapi_PBlock *pb, const char *dn, LDAPMod **m static int modify_internal_pb (Slapi_PBlock *pb) { LDAPControl **controls; - LDAPControl *pwpolicy_ctrl; + int pwpolicy_ctrl = 0; Operation *op; int opresult = 0; LDAPMod **normalized_mods = NULL; diff --git a/ldap/servers/slapd/opshared.c b/ldap/servers/slapd/opshared.c index 06ff32f6e..0f3c06812 100644 --- a/ldap/servers/slapd/opshared.c +++ b/ldap/servers/slapd/opshared.c @@ -61,7 +61,6 @@ static char *pwpolicy_lock_attrs_all [] = { "passwordRetryCount", NULL}; /* Forward declarations */ static void compute_limits (Slapi_PBlock *pb); -static int send_results (Slapi_PBlock *pb, int send_result, int *nentries); static int send_results_ext (Slapi_PBlock *pb, int send_result, int *nentries, int pagesize, unsigned int *pr_stat); static int process_entry(Slapi_PBlock *pb, Slapi_Entry *e, int send_result); @@ -1461,15 +1460,6 @@ send_results_ext(Slapi_PBlock *pb, int send_result, int *nentries, int pagesize, return rc; } -/* Iterates through results and send them to the client. - * Returns 0 if successful and -1 otherwise - */ -static int -send_results(Slapi_PBlock *pb, int send_result, int *nentries) -{ - return send_results_ext(pb, send_result, nentries, -1, NULL); -} - void op_shared_log_error_access (Slapi_PBlock *pb, const char *type, const char *dn, const char *msg) { char ebuf[BUFSIZ]; diff --git a/ldap/servers/slapd/pagedresults.c b/ldap/servers/slapd/pagedresults.c index f140933e6..e82053bc0 100644 --- a/ldap/servers/slapd/pagedresults.c +++ b/ldap/servers/slapd/pagedresults.c @@ -131,7 +131,7 @@ pagedresults_set_response_control( Slapi_PBlock *pb, int iscritical, /* begin sequence, payload, end sequence */ if (curr_search_count < 0) { - cookie_str = slapi_ch_smprintf(""); + cookie_str = slapi_ch_strdup(""); } else { cookie_str = slapi_ch_smprintf("%d", curr_search_count); } diff --git a/ldap/servers/slapd/pblock.c b/ldap/servers/slapd/pblock.c index dd8239db7..c89a64854 100644 --- a/ldap/servers/slapd/pblock.c +++ b/ldap/servers/slapd/pblock.c @@ -1082,7 +1082,7 @@ slapi_pblock_get( Slapi_PBlock *pblock, int arg, void *value ) if ( pblock->pb_plugin->plg_type != SLAPI_PLUGIN_SYNTAX ) { return( -1 ); } - (*(int *)value) = pblock->pb_plugin->plg_syntax_validate; + (*(IFP *)value) = pblock->pb_plugin->plg_syntax_validate; break; /* controls we know about */ diff --git a/ldap/servers/slapd/plugin_syntax.c b/ldap/servers/slapd/plugin_syntax.c index 3290a9547..945271ec4 100644 --- a/ldap/servers/slapd/plugin_syntax.c +++ b/ldap/servers/slapd/plugin_syntax.c @@ -278,7 +278,6 @@ slapi_entry_syntax_check( int ret = 0; int i = 0; int is_replicated_operation = 0; - int badval = 0; int syntaxcheck = config_get_syntaxcheck(); int syntaxlogging = config_get_syntaxlogging(); Slapi_Attr *prevattr = NULL; @@ -366,7 +365,6 @@ slapi_mods_syntax_check( int ret = 0; int i, j = 0; int is_replicated_operation = 0; - int badval = 0; int syntaxcheck = config_get_syntaxcheck(); int syntaxlogging = config_get_syntaxlogging(); char errtext[ BUFSIZ ]; diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 1ba7ddaef..ba18a29c6 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -1339,6 +1339,9 @@ int pagedresults_get_search_result_count(Connection *conn); int pagedresults_set_search_result_count(Connection *conn, int cnt); int pagedresults_get_with_sort(Connection *conn); int pagedresults_set_with_sort(Connection *conn, int flags); +int pagedresults_get_sort_result_code(Connection *conn); +int pagedresults_set_sort_result_code(Connection *conn, int code); +int pagedresults_set_timelimit(Connection *conn, time_t timelimit); /* * sort.c diff --git a/ldap/servers/slapd/snmp_collator.c b/ldap/servers/slapd/snmp_collator.c index 9fb629d28..9beb878a7 100644 --- a/ldap/servers/slapd/snmp_collator.c +++ b/ldap/servers/slapd/snmp_collator.c @@ -80,7 +80,9 @@ #define URL_CHARS_LEN 9 static char *make_ds_url(char *host, int port); +#ifdef DEBUG_SNMP_INTERACTION static void print_snmp_interaction_table(); +#endif /* DEBUG_SNMP_INTERACTION */ static int search_interaction_table(char *dsURL, int *isnew); static void loadConfigStats(); static Slapi_Entry *getConfigEntry( Slapi_Entry **e ); @@ -338,6 +340,8 @@ static int search_interaction_table(char *dsURL, int *isnew) return index; } + +#ifdef DEBUG_SNMP_INTERACTION /* for debuging until subagent part working, print contents of interaction table */ static void print_snmp_interaction_table() { @@ -356,6 +360,7 @@ static void print_snmp_interaction_table() fprintf(stderr, "\n"); } } +#endif /* DEBUG_SNMP_INTERACTION */ /*------------------------------------------------------------------------- * diff --git a/ldap/servers/slapd/tools/mmldif.c b/ldap/servers/slapd/tools/mmldif.c index ccc4eabd7..409ce3eda 100644 --- a/ldap/servers/slapd/tools/mmldif.c +++ b/ldap/servers/slapd/tools/mmldif.c @@ -53,6 +53,7 @@ # include <io.h> #endif +#include <nss.h> #include <pk11func.h> #include <slap.h> diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c index 2aff1e30d..672eff1d9 100644 --- a/ldap/servers/slapd/util.c +++ b/ldap/servers/slapd/util.c @@ -887,35 +887,6 @@ slapi_urlparse_err2string( int err ) #include <sasl.h> -/* copied from mozldap libldap/saslbind.c */ -static int -slapd_sasl_fail() -{ - return( SASL_FAIL ); -} - -/* copied from slapd/saslbind.c - not an easy way to share this function - between the two files */ -static int slapd_sasl_getpluginpath(sasl_conn_t *conn, const char **path) -{ - /* Try to get path from config, otherwise check for SASL_PATH environment - * variable. If neither of these are set, default to /usr/lib64/sasl2 on - * 64-bit Linux machines, and /usr/lib/sasl2 on all other platforms. - */ - char *pluginpath = config_get_saslpath(); - if ((!pluginpath) || (*pluginpath == '\0')) { - if (!(pluginpath = getenv("SASL_PATH"))) { -#if defined(LINUX) && defined(__LP64__) - pluginpath = "/usr/lib64/sasl2"; -#else - pluginpath = "/usr/lib/sasl2"; -#endif - } - } - *path = pluginpath; - return SASL_OK; -} - /* Perform LDAP init and return an LDAP* handle. If ldapurl is given, that is used as the basis for the protocol, host, port, and whether
0
c52987d295a9f4a091568d02679765f3a83beb69
389ds/389-ds-base
Ticket #443 - Deleting attribute present in nsslapd-allowed-to-delete-attrs returns Operations error Description: commit 90dd9bb3c1411daca353d055d90618e67aa1fa7e introduced an Invalid read/write. The commit meant to allow "on" and "off" as well as integer 0 and 1 in on/off type of config parameters. This patch converts the integers to "on" or "off" and pass it to config set function. https://fedorahosted.org/389/ticket/443 Reviewed by [email protected] (Thank you, Rich!!)
commit c52987d295a9f4a091568d02679765f3a83beb69 Author: Noriko Hosoi <[email protected]> Date: Thu Jan 23 18:07:56 2014 -0800 Ticket #443 - Deleting attribute present in nsslapd-allowed-to-delete-attrs returns Operations error Description: commit 90dd9bb3c1411daca353d055d90618e67aa1fa7e introduced an Invalid read/write. The commit meant to allow "on" and "off" as well as integer 0 and 1 in on/off type of config parameters. This patch converts the integers to "on" or "off" and pass it to config set function. https://fedorahosted.org/389/ticket/443 Reviewed by [email protected] (Thank you, Rich!!) diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 93e49c345..e887acec5 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -3233,8 +3233,7 @@ config_set_security( const char *attrname, char *value, char *errorbuf, int appl } static int -config_set_onoff ( const char *attrname, char *value, int *configvalue, - char *errorbuf, int apply ) +config_set_onoff(const char *attrname, char *value, int *configvalue, char *errorbuf, int apply) { int retVal = LDAP_SUCCESS; slapi_onoff_t newval = -1; @@ -3242,33 +3241,27 @@ config_set_onoff ( const char *attrname, char *value, int *configvalue, slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); #endif - if ( config_value_is_null( attrname, value, errorbuf, 0 )) { - return LDAP_OPERATIONS_ERROR; + if ( config_value_is_null( attrname, value, errorbuf, 1 )) { + return LDAP_OPERATIONS_ERROR; } CFG_ONOFF_LOCK_WRITE(slapdFrontendConfig); - if ( strcasecmp ( value, "on" ) != 0 && - strcasecmp ( value, "off") != 0 && - /* initializing the value */ - (*(int *)value != LDAP_ON) && - (*(int *)value != LDAP_OFF)) { - PR_snprintf ( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, - "%s: invalid value \"%s\". Valid values are \"on\" or \"off\".", - attrname, value ); - retVal = LDAP_OPERATIONS_ERROR; + if (strcasecmp(value, "on") && strcasecmp(value, "off")) { + PR_snprintf ( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, + "%s: invalid value \"%s\". Valid values are \"on\" or \"off\".", + attrname, value ); + retVal = LDAP_OPERATIONS_ERROR; } if ( !apply ) { - /* we can return now if we aren't applying the changes */ - return retVal; + /* we can return now if we aren't applying the changes */ + return retVal; } if ( strcasecmp ( value, "on" ) == 0 ) { - newval = LDAP_ON; + newval = LDAP_ON; } else if ( strcasecmp ( value, "off" ) == 0 ) { - newval = LDAP_OFF; - } else { /* assume it is an integer */ - newval = *(slapi_onoff_t *)value; + newval = LDAP_OFF; } #ifdef ATOMIC_GETSET_ONOFF @@ -7144,6 +7137,18 @@ config_get_listen_backlog_size() return retVal; } +static char * +config_initvalue_to_onoff(struct config_get_and_set *cgas, char *initvalbuf, size_t initvalbufsize) +{ + char *retval = NULL; + if (cgas->config_var_type == CONFIG_ON_OFF) { + slapi_onoff_t *ival = (slapi_onoff_t *)(intptr_t)cgas->initvalue; + PR_snprintf(initvalbuf, initvalbufsize, "%s", (ival && *ival) ? "on" : "off"); + retval = initvalbuf; + } + return retval; +} + /* * This function is intended to be used from the dse code modify callback. It * is "optimized" for that case because it takes a berval** of values, which is @@ -7192,12 +7197,15 @@ config_set(const char *attr, struct berval **values, char *errorbuf, int apply) default: if ((NULL == values) && config_allowed_to_delete_attrs(cgas->attr_name)) { + char initvalbuf[64]; + void *initval = cgas->initvalue; + if (cgas->config_var_type == CONFIG_ON_OFF) { + initval = (void *)config_initvalue_to_onoff(cgas, initvalbuf, sizeof(initvalbuf)); + } if (cgas->setfunc) { - retval = (cgas->setfunc)(cgas->attr_name, cgas->initvalue, - errorbuf, apply); + retval = (cgas->setfunc)(cgas->attr_name, initval, errorbuf, apply); } else if (cgas->logsetfunc) { - retval = (cgas->logsetfunc)(cgas->attr_name, cgas->initvalue, - cgas->whichlog, errorbuf, apply); + retval = (cgas->logsetfunc)(cgas->attr_name, initval, cgas->whichlog, errorbuf, apply); } else { LDAPDebug1Arg(LDAP_DEBUG_ANY, "config_set: the attribute %s is read only; "
0
d1cb6995d00f7cc5cd349dff4de2b0740d7bfb71
389ds/389-ds-base
Ticket 48133 v2 Non tombstone entry which dn starting with "nsuniqueid=...," cannot be delete Bug Description: trying to delete a non tombstone entry fails when the generated tombstone is added to the cache Fix Description: create a tombstone dn without exceptions this is an addition to the original fix for this ticket https://fedorahosted.org/389/ticket/48133 Reviewed by: Noriko, Mark - thanks
commit d1cb6995d00f7cc5cd349dff4de2b0740d7bfb71 Author: Ludwig Krispenz <[email protected]> Date: Fri Oct 21 13:20:42 2016 +0200 Ticket 48133 v2 Non tombstone entry which dn starting with "nsuniqueid=...," cannot be delete Bug Description: trying to delete a non tombstone entry fails when the generated tombstone is added to the cache Fix Description: create a tombstone dn without exceptions this is an addition to the original fix for this ticket https://fedorahosted.org/389/ticket/48133 Reviewed by: Noriko, Mark - thanks diff --git a/ldap/servers/slapd/back-ldbm/ldbm_delete.c b/ldap/servers/slapd/back-ldbm/ldbm_delete.c index 33509a5d5..72b2d29fe 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_delete.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_delete.c @@ -586,14 +586,8 @@ ldbm_back_delete( Slapi_PBlock *pb ) retval = -1; goto error_return; } - if ((0 == PL_strncmp(edn + sizeof(SLAPI_ATTR_UNIQUEID), childuniqueid, strlen(childuniqueid))) && - (*(edn + SLAPI_ATTR_UNIQUEID_LENGTH + slapi_uniqueIDSize() + 1/*=*/) == ',')) { - /* The DN already starts with "nsuniqueid=...," */ - tombstone_dn = slapi_ch_strdup(edn); - } else { - tombstone_dn = compute_entry_tombstone_dn(edn, childuniqueid); - } - + /* always create the special tombstone dn, even if it already starts with nsuniqueid */ + tombstone_dn = compute_entry_tombstone_dn(edn, childuniqueid); slapi_sdn_set_ndn_byval(&nscpEntrySDN, slapi_sdn_get_ndn(slapi_entry_get_sdn(e->ep_entry))); /* Copy the entry unique_id for URP conflict checking */
0
f2c23982d96d1c1b0516e59b3d9ed71028bf9484
389ds/389-ds-base
Issue 83 - Add an util for generating instance parameters Description: Currently, we create instance parameters (HOST_MASTER_1, PORT_MASTER_1, etc.) in _constants.py module. The commit adds generate_ds_params() to lib389.utils. The util can generate a host, port, secure port, server ID and replica ID for the selected role and instance number. I.e. inst_num=1, role="master". Fix topologies.py module to use the new util. Add create_topology() function. Remove agmts from TopologyMain, we should use agreement module for that. https://pagure.io/lib389/issue/83 Reviewed by: wibrown (Thanks!)
commit f2c23982d96d1c1b0516e59b3d9ed71028bf9484 Author: Simon Pichugin <[email protected]> Date: Mon Jul 31 09:58:25 2017 +0200 Issue 83 - Add an util for generating instance parameters Description: Currently, we create instance parameters (HOST_MASTER_1, PORT_MASTER_1, etc.) in _constants.py module. The commit adds generate_ds_params() to lib389.utils. The util can generate a host, port, secure port, server ID and replica ID for the selected role and instance number. I.e. inst_num=1, role="master". Fix topologies.py module to use the new util. Add create_topology() function. Remove agmts from TopologyMain, we should use agreement module for that. https://pagure.io/lib389/issue/83 Reviewed by: wibrown (Thanks!) diff --git a/src/lib389/lib389/_constants.py b/src/lib389/lib389/_constants.py index 05f38a32e..7e1855327 100644 --- a/src/lib389/lib389/_constants.py +++ b/src/lib389/lib389/_constants.py @@ -17,6 +17,7 @@ from lib389.properties import * INSTALL_LATEST_CONFIG = '999999999' +ROLE_STANDALONE = "standalone" REPLICAROLE_MASTER = "master" REPLICAROLE_HUB = "hub" REPLICAROLE_CONSUMER = "consumer" diff --git a/src/lib389/lib389/agreement.py b/src/lib389/lib389/agreement.py index 666f5b289..eb7afc73e 100644 --- a/src/lib389/lib389/agreement.py +++ b/src/lib389/lib389/agreement.py @@ -447,6 +447,9 @@ class Agreement(object): self.log.warning("create: suffix is missing") raise InvalidArgumentError('suffix is mandatory') + if not properties: + properties = {} + # Compute the normalized suffix to be set in RA entry properties[RA_SUFFIX] = normalizeDN(suffix) diff --git a/src/lib389/lib389/tests/idm/user_compare_m2Repl_test.py b/src/lib389/lib389/tests/idm/user_compare_m2Repl_test.py index 8e7b799b9..19ac1c903 100644 --- a/src/lib389/lib389/tests/idm/user_compare_m2Repl_test.py +++ b/src/lib389/lib389/tests/idm/user_compare_m2Repl_test.py @@ -38,7 +38,7 @@ def test_user_compare_m2Repl(topology_m2): m1 = topology_m2.ms.get('master1') m2 = topology_m2.ms.get('master2') - m1_m2_agmtdn = topology_m2.ms.get("master1_agmts").get("m1_m2") + m1_m2_agmtdn = m1.agreement.list(suffix=DEFAULT_SUFFIX)[0].dn m1_users = UserAccounts(m1, DEFAULT_SUFFIX) m2_users = UserAccounts(m2, DEFAULT_SUFFIX) diff --git a/src/lib389/lib389/topologies.py b/src/lib389/lib389/topologies.py index 19d121d7b..161d887fc 100644 --- a/src/lib389/lib389/topologies.py +++ b/src/lib389/lib389/topologies.py @@ -6,15 +6,18 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- # +import os import logging -import sys import time import pytest from lib389 import DirSrv -from lib389._constants import * -from lib389.properties import * +from lib389.utils import generate_ds_params +from lib389.replica import Replicas +from lib389._constants import (args_instance, SER_HOST, SER_PORT, SER_SERVERID_PROP, SER_CREATION_SUFFIX, + ROLE_STANDALONE, REPLICAROLE_MASTER, REPLICAROLE_HUB, REPLICAROLE_CONSUMER, + DEFAULT_SUFFIX, REPLICA_ID) DEBUGGING = os.getenv('DEBUGGING', default=False) if DEBUGGING: @@ -24,10 +27,107 @@ else: log = logging.getLogger(__name__) +def create_topology(topo_dict): + """Create a requested topology + + @param topo_dict - dictionary {REPLICAROLE: number_of_insts} + @return - dictionary {serverid: topology_instance} + """ + + if not topo_dict: + ValueError("You need to specify the dict. For instance: {ROLE_STANDALONE: 1}") + + instances = {} + ms = {} + hs = {} + cs = {} + ins = {} + replica_dict = {} + agmts = {} + + # Create instances + for role in topo_dict.keys(): + for inst_num in range(1, topo_dict[role]+1): + instance_data = generate_ds_params(inst_num, role) + if DEBUGGING: + instance = DirSrv(verbose=True) + else: + instance = DirSrv(verbose=False) + # TODO: Put 'args_instance' to generate_ds_params. + # Also, we need to keep in mind that the function returns + # SER_SECURE_PORT and REPLICA_ID that are not used in + # the instance creation here. + args_instance[SER_HOST] = instance_data[SER_HOST] + args_instance[SER_PORT] = instance_data[SER_PORT] + args_instance[SER_SERVERID_PROP] = instance_data[SER_SERVERID_PROP] + args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX + args_copied = args_instance.copy() + instance.allocate(args_copied) + instance_exists = instance.exists() + if instance_exists: + instance.delete() + instance.create() + instance.open() + if role == ROLE_STANDALONE: + ins[instance.serverid] = instance + instances.update(ins) + if role == REPLICAROLE_MASTER: + ms[instance.serverid] = instance + instances.update(ms) + if role == REPLICAROLE_HUB: + hs[instance.serverid] = instance + instances.update(hs) + if role == REPLICAROLE_CONSUMER: + cs[instance.serverid] = instance + instances.update(cs) + log.info("Instance with parameters {} was created.".format(args_copied)) + + # Set up replication + if role in (REPLICAROLE_MASTER, REPLICAROLE_HUB, REPLICAROLE_CONSUMER): + replicas = Replicas(instance) + replica = replicas.enable(DEFAULT_SUFFIX, role, instance_data[REPLICA_ID]) + replica_dict[replica] = instance + + # Create agreements + for role_from in topo_dict.keys(): + for inst_num_from in range(1, topo_dict[role]+1): + roles_to = [REPLICAROLE_HUB, REPLICAROLE_CONSUMER] + if role == REPLICAROLE_MASTER: + roles_to.append(REPLICAROLE_MASTER) + + for role_to in [role for role in topo_dict if role in roles_to]: + for inst_num_to in range(1, topo_dict[role]+1): + # Exclude our instance + if role_from != role_to or inst_num_from != inst_num_to: + inst_from = instances["{}{}".format(role_from, inst_num_from)] + inst_to = instances["{}{}".format(role_to, inst_num_to)] + agmt = inst_from.agreement.create(suffix=DEFAULT_SUFFIX, + host=inst_to.host, + port=inst_to.port) + agmts[agmt] = (inst_from, inst_to) + + # Allow the replicas to get situated with the new agreements + if agmts: + time.sleep(5) + + # Initialize all the agreements + for agmt, insts in agmts.items(): + insts[0].agreement.init(DEFAULT_SUFFIX, insts[1].host, insts[1].port) + insts[0].waitForReplInit(agmt) + + # Clear out the tmp dir + for instance in instances.values(): + instance.clearTmpDir(__file__) + + if "standalone1" in instances and len(instances) == 1: + return TopologyMain(standalones=instances["standalone1"]) + else: + return TopologyMain(standalones=ins, masters=ms, hubs=hs, consumers=cs) + + class TopologyMain(object): - def __init__(self, standalones=None, masters=None, - consumers=None, hubs=None): - insts_with_agreements = {} + def __init__(self, standalones=None, masters=None, consumers=None, hubs=None): + self.all_insts = {} if standalones: if isinstance(standalones, dict): @@ -36,27 +136,25 @@ class TopologyMain(object): self.standalone = standalones if masters: self.ms = masters - insts_with_agreements.update(self.ms) + self.all_insts.update(self.ms) if consumers: self.cs = consumers - insts_with_agreements.update(self.cs) + self.all_insts.update(self.cs) if hubs: self.hs = hubs - insts_with_agreements.update(self.hs) - - self._insts = {name: inst for name, inst in insts_with_agreements.items() if not name.endswith('agmts')} + self.all_insts.update(self.hs) def pause_all_replicas(self): """Pause all agreements in the class instance""" - for inst in self._insts.values(): + for inst in self.all_insts.values(): for agreement in inst.agreement.list(suffix=DEFAULT_SUFFIX): inst.agreement.pause(agreement.dn) def resume_all_replicas(self): """Resume all agreements in the class instance""" - for inst in self._insts.values(): + for inst in self.all_insts.values(): for agreement in inst.agreement.list(suffix=DEFAULT_SUFFIX): inst.agreement.resume(agreement.dn) @@ -65,1119 +163,157 @@ class TopologyMain(object): def topology_st(request): """Create DS standalone instance""" - if DEBUGGING: - standalone = DirSrv(verbose=True) - else: - standalone = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE1 - args_instance[SER_PORT] = PORT_STANDALONE1 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone = args_instance.copy() - standalone.allocate(args_standalone) - instance_standalone = standalone.exists() - if instance_standalone: - standalone.delete() - standalone.create() - standalone.open() + topology = create_topology({ROLE_STANDALONE: 1}) def fin(): if DEBUGGING: - standalone.stop() + topology.standalone.stop() else: - standalone.delete() - + topology.standalone.delete() request.addfinalizer(fin) - return TopologyMain(standalones=standalone) + return topology @pytest.fixture(scope="module") def topology_i2(request): """Create two instance DS deployment""" - if DEBUGGING: - standalone1 = DirSrv(verbose=True) - else: - standalone1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE1 - args_instance[SER_PORT] = PORT_STANDALONE1 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone1 = args_instance.copy() - standalone1.allocate(args_standalone1) - instance_standalone1 = standalone1.exists() - if instance_standalone1: - standalone1.delete() - standalone1.create() - standalone1.open() - - if DEBUGGING: - standalone2 = DirSrv(verbose=True) - else: - standalone2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE2 - args_instance[SER_PORT] = PORT_STANDALONE2 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone2 = args_instance.copy() - standalone2.allocate(args_standalone2) - instance_standalone2 = standalone2.exists() - if instance_standalone2: - standalone2.delete() - standalone2.create() - standalone2.open() + topology = create_topology({ROLE_STANDALONE: 2}) def fin(): if DEBUGGING: - standalone1.stop() - standalone2.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - standalone1.delete() - standalone2.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - return TopologyMain(standalones={"standalone1": standalone1, "standalone2": standalone2}) + return topology @pytest.fixture(scope="module") def topology_i3(request): """Create three instance DS deployment""" - if DEBUGGING: - standalone1 = DirSrv(verbose=True) - else: - standalone1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE1 - args_instance[SER_PORT] = PORT_STANDALONE1 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone1 = args_instance.copy() - standalone1.allocate(args_standalone1) - instance_standalone1 = standalone1.exists() - if instance_standalone1: - standalone1.delete() - standalone1.create() - standalone1.open() - - if DEBUGGING: - standalone2 = DirSrv(verbose=True) - else: - standalone2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE2 - args_instance[SER_PORT] = PORT_STANDALONE2 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone2 = args_instance.copy() - standalone2.allocate(args_standalone2) - instance_standalone2 = standalone2.exists() - if instance_standalone2: - standalone2.delete() - standalone2.create() - standalone2.open() - - if DEBUGGING: - standalone3 = DirSrv(verbose=True) - else: - standalone3 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_STANDALONE3 - args_instance[SER_PORT] = PORT_STANDALONE3 - args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE3 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_standalone3 = args_instance.copy() - standalone3.allocate(args_standalone3) - instance_standalone3 = standalone3.exists() - if instance_standalone3: - standalone3.delete() - standalone3.create() - standalone3.open() + topology = create_topology({ROLE_STANDALONE: 3}) def fin(): if DEBUGGING: - standalone1.stop() - standalone2.stop() - standalone3.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - standalone1.delete() - standalone2.delete() - standalone3.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - return TopologyMain(standalones={"standalone1": standalone1, - "standalone2": standalone2, - "standalone3": standalone3}) + return topology @pytest.fixture(scope="module") def topology_m1c1(request): """Create Replication Deployment with one master and one consumer""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_1) - - # Creating consumer 1... - if DEBUGGING: - consumer1 = DirSrv(verbose=True) - else: - consumer1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_CONSUMER_1 - args_instance[SER_PORT] = PORT_CONSUMER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_CONSUMER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_consumer = args_instance.copy() - consumer1.allocate(args_consumer) - instance_consumer1 = consumer1.exists() - if instance_consumer1: - consumer1.delete() - consumer1.create() - consumer1.open() - consumer1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_CONSUMER, - replicaId=CONSUMER_REPLICAID) + topology = create_topology({REPLICAROLE_MASTER: 1, + REPLICAROLE_CONSUMER: 1}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) def fin(): if DEBUGGING: - master1.stop() - consumer1.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - consumer1.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to consumer 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(consumer1.host, str(consumer1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_c1_agmt = master1.agreement.create(suffix=SUFFIX, host=consumer1.host, - port=consumer1.port, properties=properties) - if not m1_c1_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_c1_agmt)) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_CONSUMER_1, PORT_CONSUMER_1) - master1.waitForReplInit(m1_c1_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, consumer1): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_c1": m1_c1_agmt}}, - consumers={"consumer1": consumer1}) + return topology @pytest.fixture(scope="module") def topology_m1h1c1(request): """Create Replication Deployment with one master, one consumer and one hub""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_1) - - # Creating hub 1... - if DEBUGGING: - hub1 = DirSrv(verbose=True) - else: - hub1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_HUB_1 - args_instance[SER_PORT] = PORT_HUB_1 - args_instance[SER_SERVERID_PROP] = SERVERID_HUB_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_hub = args_instance.copy() - hub1.allocate(args_hub) - instance_hub1 = hub1.exists() - if instance_hub1: - hub1.delete() - hub1.create() - hub1.open() - hub1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_HUB, - replicaId=REPLICAID_HUB_1) - - # Creating consumer 1... - if DEBUGGING: - consumer1 = DirSrv(verbose=True) - else: - consumer1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_CONSUMER_1 - args_instance[SER_PORT] = PORT_CONSUMER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_CONSUMER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_consumer = args_instance.copy() - consumer1.allocate(args_consumer) - instance_consumer1 = consumer1.exists() - if instance_consumer1: - consumer1.delete() - consumer1.create() - consumer1.open() - consumer1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_CONSUMER, - replicaId=CONSUMER_REPLICAID) + topology = create_topology({REPLICAROLE_MASTER: 1, + REPLICAROLE_HUB: 1, + REPLICAROLE_CONSUMER: 1}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) def fin(): if DEBUGGING: - master1.stop() - hub1.stop() - consumer1.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - hub1.delete() - consumer1.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to hub 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(hub1.host, str(hub1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_h1_agmt = master1.agreement.create(suffix=SUFFIX, host=hub1.host, - port=hub1.port, properties=properties) - if not m1_h1_agmt: - log.fatal("Fail to create a master -> hub replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_h1_agmt)) - - # Creating agreement from hub 1 to consumer 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(consumer1.host, str(consumer1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - h1_c1_agmt = hub1.agreement.create(suffix=SUFFIX, host=consumer1.host, - port=consumer1.port, properties=properties) - if not h1_c1_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("{} created".format(h1_c1_agmt)) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_HUB_1, PORT_HUB_1) - master1.waitForReplInit(m1_h1_agmt) - hub1.agreement.init(SUFFIX, HOST_CONSUMER_1, PORT_CONSUMER_1) - hub1.waitForReplInit(h1_c1_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, consumer1): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_h1": m1_h1_agmt}}, - hubs={"hub1": hub1, "hub1_agmts": {"h1_c1": h1_c1_agmt}}, - consumers={"consumer1": consumer1}) + return topology @pytest.fixture(scope="module") def topology_m2(request): """Create Replication Deployment with two masters""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_1) - - # Creating master 2... - if DEBUGGING: - master2 = DirSrv(verbose=True) - else: - master2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_2 - args_instance[SER_PORT] = PORT_MASTER_2 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master2.allocate(args_master) - instance_master2 = master2.exists() - if instance_master2: - master2.delete() - master2.create() - master2.open() - master2.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_2) + topology = create_topology({REPLICAROLE_MASTER: 2}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.ms["master2"]) def fin(): if DEBUGGING: - master1.stop() - master2.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - master2.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to master 2 - properties = {RA_NAME: 'meTo_{}:{}'.format(master2.host, str(master2.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m2_agmt = master1.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m1_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m2_agmt)) - - # Creating agreement from master 2 to master 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(master1.host, str(master1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m1_agmt = master2.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m2_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m1_agmt)) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_MASTER_2, PORT_MASTER_2) - master1.waitForReplInit(m1_m2_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, master2): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_m2": m1_m2_agmt}, - "master2": master2, "master2_agmts": {"m2_m1": m2_m1_agmt}}) + return topology @pytest.fixture(scope="module") def topology_m3(request): """Create Replication Deployment with three masters""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_1) - - # Creating master 2... - if DEBUGGING: - master2 = DirSrv(verbose=True) - else: - master2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_2 - args_instance[SER_PORT] = PORT_MASTER_2 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master2.allocate(args_master) - instance_master2 = master2.exists() - if instance_master2: - master2.delete() - master2.create() - master2.open() - master2.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_2) - - # Creating master 3... - if DEBUGGING: - master3 = DirSrv(verbose=True) - else: - master3 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_3 - args_instance[SER_PORT] = PORT_MASTER_3 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_3 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master3.allocate(args_master) - instance_master3 = master3.exists() - if instance_master3: - master3.delete() - master3.create() - master3.open() - master3.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_3) + topology = create_topology({REPLICAROLE_MASTER: 3}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.ms["master3"]) def fin(): if DEBUGGING: - master1.stop() - master2.stop() - master3.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - master2.delete() - master3.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to master 2 - properties = {RA_NAME: 'meTo_{}:{}'.format(master2.host, str(master2.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m2_agmt = master1.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m1_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m2_agmt)) - - # Creating agreement from master 1 to master 3 - properties = {RA_NAME: 'meTo_{}:{}'.format(master3.host, str(master3.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m3_agmt = master1.agreement.create(suffix=SUFFIX, host=master3.host, - port=master3.port, properties=properties) - if not m1_m3_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m3_agmt)) - - # Creating agreement from master 2 to master 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(master1.host, str(master1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m1_agmt = master2.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m2_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m1_agmt)) - - # Creating agreement from master 2 to master 3 - properties = {RA_NAME: 'meTo_{}:{}'.format(master3.host, str(master3.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m3_agmt = master2.agreement.create(suffix=SUFFIX, host=master3.host, - port=master3.port, properties=properties) - if not m2_m3_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m3_agmt)) - - # Creating agreement from master 3 to master 1 - properties = {RA_NAME: 'meTo_{}:{}'.format(master1.host, str(master1.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m3_m1_agmt = master3.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m3_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m3_m1_agmt)) - - # Creating agreement from master 3 to master 2 - properties = {RA_NAME: 'meTo_{}:{}'.format(master2.host, str(master2.port)), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m3_m2_agmt = master3.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m3_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m3_m2_agmt)) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_MASTER_2, PORT_MASTER_2) - master1.waitForReplInit(m1_m2_agmt) - master1.agreement.init(SUFFIX, HOST_MASTER_3, PORT_MASTER_3) - master1.waitForReplInit(m1_m3_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, master2): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_m2": m1_m2_agmt, - "m1_m3": m1_m3_agmt}, - "master2": master2, "master2_agmts": {"m2_m1": m2_m1_agmt, - "m2_m3": m2_m3_agmt}, - "master3": master3, "master3_agmts": {"m3_m1": m3_m1_agmt, - "m3_m2": m3_m2_agmt}}) + return topology @pytest.fixture(scope="module") def topology_m4(request): """Create Replication Deployment with four masters""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_1) - - # Creating master 2... - if DEBUGGING: - master2 = DirSrv(verbose=True) - else: - master2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_2 - args_instance[SER_PORT] = PORT_MASTER_2 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master2.allocate(args_master) - instance_master2 = master2.exists() - if instance_master2: - master2.delete() - master2.create() - master2.open() - master2.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_2) - - # Creating master 3... - if DEBUGGING: - master3 = DirSrv(verbose=True) - else: - master3 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_3 - args_instance[SER_PORT] = PORT_MASTER_3 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_3 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master3.allocate(args_master) - instance_master3 = master3.exists() - if instance_master3: - master3.delete() - master3.create() - master3.open() - master3.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_3) - - # Creating master 4... - if DEBUGGING: - master4 = DirSrv(verbose=True) - else: - master4 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_4 - args_instance[SER_PORT] = PORT_MASTER_4 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_4 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master4.allocate(args_master) - instance_master4 = master4.exists() - if instance_master4: - master4.delete() - master4.create() - master4.open() - master4.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, - replicaId=REPLICAID_MASTER_4) + topology = create_topology({REPLICAROLE_MASTER: 4}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.ms["master4"]) def fin(): if DEBUGGING: - master1.stop() - master2.stop() - master3.stop() - master4.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - master2.delete() - master3.delete() - master4.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to master 2 - properties = {RA_NAME: 'meTo_' + master2.host + ':' + str(master2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m2_agmt = master1.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m1_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m2_agmt)) - - # Creating agreement from master 1 to master 3 - properties = {RA_NAME: 'meTo_' + master3.host + ':' + str(master3.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m3_agmt = master1.agreement.create(suffix=SUFFIX, host=master3.host, - port=master3.port, properties=properties) - if not m1_m3_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m3_agmt)) - - # Creating agreement from master 1 to master 4 - properties = {RA_NAME: 'meTo_' + master4.host + ':' + str(master4.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m4_agmt = master1.agreement.create(suffix=SUFFIX, host=master4.host, - port=master4.port, properties=properties) - if not m1_m4_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m1_m4_agmt)) - - # Creating agreement from master 2 to master 1 - properties = {RA_NAME: 'meTo_' + master1.host + ':' + str(master1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m1_agmt = master2.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m2_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m1_agmt)) - - # Creating agreement from master 2 to master 3 - properties = {RA_NAME: 'meTo_' + master3.host + ':' + str(master3.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m3_agmt = master2.agreement.create(suffix=SUFFIX, host=master3.host, - port=master3.port, properties=properties) - if not m2_m3_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m3_agmt)) - - # Creating agreement from master 2 to master 4 - properties = {RA_NAME: 'meTo_' + master4.host + ':' + str(master4.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m4_agmt = master2.agreement.create(suffix=SUFFIX, host=master4.host, - port=master4.port, properties=properties) - if not m2_m4_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m2_m4_agmt)) - - # Creating agreement from master 3 to master 1 - properties = {RA_NAME: 'meTo_' + master1.host + ':' + str(master1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m3_m1_agmt = master3.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m3_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m3_m1_agmt)) - - # Creating agreement from master 3 to master 2 - properties = {RA_NAME: 'meTo_' + master2.host + ':' + str(master2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m3_m2_agmt = master3.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m3_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m3_m2_agmt)) - - # Creating agreement from master 3 to master 4 - properties = {RA_NAME: 'meTo_' + master4.host + ':' + str(master4.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m3_m4_agmt = master3.agreement.create(suffix=SUFFIX, host=master4.host, - port=master4.port, properties=properties) - if not m3_m4_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m3_m4_agmt)) - - # Creating agreement from master 4 to master 1 - properties = {RA_NAME: 'meTo_' + master1.host + ':' + str(master1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m4_m1_agmt = master4.agreement.create(suffix=SUFFIX, host=master1.host, - port=master1.port, properties=properties) - if not m4_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m4_m1_agmt)) - - # Creating agreement from master 4 to master 2 - properties = {RA_NAME: 'meTo_' + master2.host + ':' + str(master2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m4_m2_agmt = master4.agreement.create(suffix=SUFFIX, host=master2.host, - port=master2.port, properties=properties) - if not m4_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m4_m2_agmt)) - - # Creating agreement from master 4 to master 3 - properties = {RA_NAME: 'meTo_' + master3.host + ':' + str(master3.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m4_m3_agmt = master4.agreement.create(suffix=SUFFIX, host=master3.host, - port=master3.port, properties=properties) - if not m4_m3_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("{} created".format(m4_m3_agmt)) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_MASTER_2, PORT_MASTER_2) - master1.waitForReplInit(m1_m2_agmt) - master1.agreement.init(SUFFIX, HOST_MASTER_3, PORT_MASTER_3) - master1.waitForReplInit(m1_m3_agmt) - master1.agreement.init(SUFFIX, HOST_MASTER_4, PORT_MASTER_4) - master1.waitForReplInit(m1_m4_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, master2): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_m2": m1_m2_agmt, - "m1_m3": m1_m3_agmt, - "m1_m4": m1_m4_agmt}, - "master2": master2, "master2_agmts": {"m2_m1": m2_m1_agmt, - "m2_m3": m2_m3_agmt, - "m2_m4": m2_m4_agmt}, - "master3": master3, "master3_agmts": {"m3_m1": m3_m1_agmt, - "m3_m2": m3_m2_agmt, - "m3_m4": m3_m4_agmt}, - "master4": master4, "master4_agmts": {"m4_m1": m4_m1_agmt, - "m4_m2": m4_m2_agmt, - "m4_m3": m4_m3_agmt}}) + return topology @pytest.fixture(scope="module") def topology_m2c2(request): """Create Replication Deployment with two masters and two consumers""" - # Creating master 1... - if DEBUGGING: - master1 = DirSrv(verbose=True) - else: - master1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_1 - args_instance[SER_PORT] = PORT_MASTER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master1.allocate(args_master) - instance_master1 = master1.exists() - if instance_master1: - master1.delete() - master1.create() - master1.open() - master1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, replicaId=REPLICAID_MASTER_1) - - # Creating master 2... - if DEBUGGING: - master2 = DirSrv(verbose=True) - else: - master2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_MASTER_2 - args_instance[SER_PORT] = PORT_MASTER_2 - args_instance[SER_SERVERID_PROP] = SERVERID_MASTER_2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_master = args_instance.copy() - master2.allocate(args_master) - instance_master2 = master2.exists() - if instance_master2: - master2.delete() - master2.create() - master2.open() - master2.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_MASTER, replicaId=REPLICAID_MASTER_2) - - # Creating consumer 1... - if DEBUGGING: - consumer1 = DirSrv(verbose=True) - else: - consumer1 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_CONSUMER_1 - args_instance[SER_PORT] = PORT_CONSUMER_1 - args_instance[SER_SERVERID_PROP] = SERVERID_CONSUMER_1 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_consumer = args_instance.copy() - consumer1.allocate(args_consumer) - instance_consumer1 = consumer1.exists() - if instance_consumer1: - consumer1.delete() - consumer1.create() - consumer1.open() - consumer1.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_CONSUMER, replicaId=CONSUMER_REPLICAID) - - # Creating consumer 2... - if DEBUGGING: - consumer2 = DirSrv(verbose=True) - else: - consumer2 = DirSrv(verbose=False) - args_instance[SER_HOST] = HOST_CONSUMER_2 - args_instance[SER_PORT] = PORT_CONSUMER_2 - args_instance[SER_SERVERID_PROP] = SERVERID_CONSUMER_2 - args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX - args_consumer = args_instance.copy() - consumer2.allocate(args_consumer) - instance_consumer2 = consumer2.exists() - if instance_consumer2: - consumer2.delete() - consumer2.create() - consumer2.open() - consumer2.replica.enableReplication(suffix=SUFFIX, role=REPLICAROLE_CONSUMER, replicaId=CONSUMER_REPLICAID) + topology = create_topology({REPLICAROLE_MASTER: 2, + REPLICAROLE_CONSUMER: 2}) + replicas = Replicas(topology.ms["master1"]) + replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"]) def fin(): if DEBUGGING: - master1.stop() - master2.stop() - consumer1.stop() - consumer2.stop() + map(lambda inst: inst.stop(), topology.all_insts.values()) else: - master1.delete() - master2.delete() - consumer1.delete() - consumer2.delete() - + map(lambda inst: inst.delete(), topology.all_insts.values()) request.addfinalizer(fin) - # Create all the agreements - # Creating agreement from master 1 to master 2 - properties = {RA_NAME: 'meTo_' + master2.host + ':' + str(master2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_m2_agmt = master1.agreement.create(suffix=SUFFIX, host=master2.host, port=master2.port, properties=properties) - if not m1_m2_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("%s created" % m1_m2_agmt) - - # Creating agreement from master 2 to master 1 - properties = {RA_NAME: 'meTo_' + master1.host + ':' + str(master1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_m1_agmt = master2.agreement.create(suffix=SUFFIX, host=master1.host, port=master1.port, properties=properties) - if not m2_m1_agmt: - log.fatal("Fail to create a master -> master replica agreement") - sys.exit(1) - log.debug("%s created" % m2_m1_agmt) - - # Creating agreement from master 1 to consumer 1 - properties = {RA_NAME: 'meTo_' + consumer1.host + ':' + str(consumer1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_c1_agmt = master1.agreement.create(suffix=SUFFIX, host=consumer1.host, port=consumer1.port, - properties=properties) - if not m1_c1_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("%s created" % m1_c1_agmt) - - # Creating agreement from master 1 to consumer 2 - properties = {RA_NAME: 'meTo_' + consumer2.host + ':' + str(consumer2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m1_c2_agmt = master1.agreement.create(suffix=SUFFIX, host=consumer2.host, port=consumer2.port, - properties=properties) - if not m1_c2_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("%s created" % m1_c2_agmt) - - # Creating agreement from master 2 to consumer 1 - properties = {RA_NAME: 'meTo_' + consumer1.host + ':' + str(consumer1.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_c1_agmt = master2.agreement.create(suffix=SUFFIX, host=consumer1.host, port=consumer1.port, - properties=properties) - if not m2_c1_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("%s created" % m2_c1_agmt) - - # Creating agreement from master 2 to consumer 2 - properties = {RA_NAME: 'meTo_' + consumer2.host + ':' + str(consumer2.port), - RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], - RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], - RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], - RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} - m2_c2_agmt = master2.agreement.create(suffix=SUFFIX, host=consumer2.host, port=consumer2.port, - properties=properties) - if not m2_c2_agmt: - log.fatal("Fail to create a hub -> consumer replica agreement") - sys.exit(1) - log.debug("%s created" % m2_c2_agmt) - - # Allow the replicas to get situated with the new agreements... - time.sleep(5) - - # Initialize all the agreements - master1.agreement.init(SUFFIX, HOST_MASTER_2, PORT_MASTER_2) - master1.waitForReplInit(m1_m2_agmt) - master1.agreement.init(SUFFIX, HOST_CONSUMER_1, PORT_CONSUMER_1) - master1.waitForReplInit(m1_c1_agmt) - master1.agreement.init(SUFFIX, HOST_CONSUMER_2, PORT_CONSUMER_2) - master1.waitForReplInit(m1_c2_agmt) - - # Check replication is working... - if master1.testReplication(DEFAULT_SUFFIX, consumer1): - log.info('Replication is working.') - else: - log.fatal('Replication is not working.') - assert False - - # Clear out the tmp dir - master1.clearTmpDir(__file__) - - return TopologyMain(masters={"master1": master1, "master1_agmts": {"m1_m2": m1_m2_agmt, - "m1_c1": m1_c1_agmt, - "m1_c2": m1_c2_agmt}, - "master2": master2, "master2_agmts": {"m2_m1": m2_m1_agmt, - "m2_c1": m2_c1_agmt, - "m2_c2": m2_c2_agmt}}, - consumers={"consumer1": consumer1, "consumer2": consumer2}) + return topology diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index e022d0f03..5cb3230e0 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -38,11 +38,14 @@ from contextlib import closing import lib389 from lib389.paths import Paths -from lib389._constants import DEFAULT_USER, VALGRIND_WRAPPER, DN_CONFIG, CFGSUFFIX +from lib389._constants import ( + DEFAULT_USER, VALGRIND_WRAPPER, DN_CONFIG, CFGSUFFIX, LOCALHOST, ROLE_STANDALONE, + REPLICAROLE_MASTER, REPLICAROLE_HUB, REPLICAROLE_CONSUMER, CONSUMER_REPLICAID + ) from lib389.properties import ( SER_HOST, SER_USER_ID, SER_GROUP_ID, SER_STRICT_HOSTNAME_CHECKING, SER_PORT, SER_ROOT_DN, SER_ROOT_PW, SER_SERVERID_PROP, SER_CREATION_SUFFIX, - SER_INST_SCRIPTS_ENABLED + SER_INST_SCRIPTS_ENABLED, SER_SECURE_PORT, REPLICA_ID ) MAJOR, MINOR, _, _, _ = sys.version_info @@ -744,6 +747,49 @@ def formatInfData(args): return content +def generate_ds_params(inst_num, role=ROLE_STANDALONE): + """Generate a host, port, secure port, server ID and replica ID + for the selected role and instance number. I.e. inst_num=1, role="master". + + @param inst_num - an instance number in a range from 1 to 99 + @param role - ROLE_STANDALONE, REPLICAROLE_MASTER, REPLICAROLE_HUB, REPLICAROLE_CONSUMER + @return - the dict with next keys: host, port, secure port, server id and replica id + """ + + if inst_num not in range(1, 100): + raise ValueError("Instance number should be in a range from 1 to 99") + + if role not in (ROLE_STANDALONE, REPLICAROLE_MASTER, REPLICAROLE_HUB, REPLICAROLE_CONSUMER): + raise ValueError('Role should be {}, {}, {}, {}'.format(ROLE_STANDALONE, REPLICAROLE_MASTER, + REPLICAROLE_HUB, REPLICAROLE_CONSUMER)) + + instance_data = {} + relevant_num = 38900 + + # Set relevant number for ports + if role == REPLICAROLE_MASTER: + relevant_num += 100 + elif role == REPLICAROLE_HUB: + relevant_num += 200 + elif role == REPLICAROLE_CONSUMER: + relevant_num += 300 + + # Define replica ID + if role == REPLICAROLE_MASTER: + replica_id = inst_num + else: + replica_id = CONSUMER_REPLICAID + + # Fill the dict with data + instance_data[SER_HOST] = LOCALHOST + instance_data[SER_PORT] = relevant_num + inst_num + instance_data[SER_SECURE_PORT] = relevant_num + inst_num + 24700 + instance_data[SER_SERVERID_PROP] = "{}{}".format(role, inst_num) + instance_data[REPLICA_ID] = replica_id + + return instance_data + + def get_ds_version(): """ Return version of ns-slapd installed on this system. This is determined by the defaults.inf @@ -755,14 +801,17 @@ def get_ds_version(): p = Paths() return p.version + def ds_is_older(ver): """Return True if current version of ns-slapd is older than provided version""" return get_ds_version() < ver + def ds_is_newer(ver): return get_ds_version() >= ver + def getDateTime(): """ Return the date and time: @@ -786,25 +835,31 @@ def ensure_bytes(val): return val.encode() return val + def ensure_str(val): if val != None and type(val) != str: return val.decode('utf-8') return val + def ensure_int(val): if val is not None and not isinstance(val, int): return int(val) return val + def ensure_list_bytes(val): return [ensure_bytes(v) for v in val] + def ensure_list_str(val): return [ensure_str(v) for v in val] + def ensure_list_int(val): return [ensure_int(v) for v in val] + def ensure_dict_str(val): if MAJOR <= 2: return val
0
6af610276381854408dfa3249f7afb3a38a8ad19
389ds/389-ds-base
Pick up new Admin Server component
commit 6af610276381854408dfa3249f7afb3a38a8ad19 Author: Nathan Kinder <[email protected]> Date: Thu Mar 31 04:52:15 2005 +0000 Pick up new Admin Server component diff --git a/component_versions.mk b/component_versions.mk index d0abbef6a..7fb79378e 100644 --- a/component_versions.mk +++ b/component_versions.mk @@ -90,7 +90,7 @@ endif # admin server ifndef ADM_RELDATE - ADM_RELDATE = 20050324 + ADM_RELDATE = 20050330 endif ifndef ADM_VERSDIR ADM_VERSDIR = adminserver/70$(BUILD_MODE) diff --git a/internal_comp_deps.mk b/internal_comp_deps.mk index c4f79deca..67309632b 100644 --- a/internal_comp_deps.mk +++ b/internal_comp_deps.mk @@ -670,8 +670,8 @@ ADMIN_REL_DATE = $(ADM_VERSION) ADMIN_FILE = admserv.tar.gz ADMIN_FILE_TAR = admserv.tar ADMSDKOBJDIR = $(NSCONFIG)$(NSOBJDIR_TAG).OBJ -#IMPORTADMINSRV_BASE=$(COMPONENTS_DIR)/$(ADMIN_REL)/$(ADMIN_REL_DATE) -IMPORTADMINSRV_BASE=$(COMPONENTS_DIR_DEV)/$(ADMIN_REL)/$(ADMIN_REL_DATE) +IMPORTADMINSRV_BASE=$(COMPONENTS_DIR)/$(ADMIN_REL)/$(ADMIN_REL_DATE) +#IMPORTADMINSRV_BASE=$(COMPONENTS_DIR_DEV)/$(ADMIN_REL)/$(ADMIN_REL_DATE) IMPORTADMINSRV = $(IMPORTADMINSRV_BASE)/$(NSOBJDIR_NAME_32) ADMSERV_DIR=$(ABS_ROOT_PARENT)/dist/$(NSOBJDIR_NAME)/admserv ADMSERV_DEP = $(ADMSERV_DIR)/setup$(EXE_SUFFIX)
0
ff7d08dc8bd356df7d29c771da420aec2e099e2d
389ds/389-ds-base
Allow anonymous access to be disabled. This adds a new config switch (nsslapd-allow-anonymous-access) that allows one to restrict all anonymous access. When this is enabled, the connection displatch code will only allow BIND operations through for an unauthenticated user. The BIND code will only allow the operation through if it's not an anonymous or unauthenticated BIND. I also fixed a missing capability in the SELinux policy that I ran into while testing this patch.
commit ff7d08dc8bd356df7d29c771da420aec2e099e2d Author: Nathan Kinder <[email protected]> Date: Thu Sep 24 12:02:29 2009 -0700 Allow anonymous access to be disabled. This adds a new config switch (nsslapd-allow-anonymous-access) that allows one to restrict all anonymous access. When this is enabled, the connection displatch code will only allow BIND operations through for an unauthenticated user. The BIND code will only allow the operation through if it's not an anonymous or unauthenticated BIND. I also fixed a missing capability in the SELinux policy that I ran into while testing this patch. diff --git a/ldap/admin/src/scripts/DSMigration.pm.in b/ldap/admin/src/scripts/DSMigration.pm.in index c0a7614df..64e066b73 100644 --- a/ldap/admin/src/scripts/DSMigration.pm.in +++ b/ldap/admin/src/scripts/DSMigration.pm.in @@ -101,6 +101,7 @@ my %ignoreOld = 'nsslapd-plugin-depends-on-named' => 'nsslapd-plugin-depends-on-named', # these are new attrs that we should just pass through 'nsslapd-allow-unauthenticated-binds' => 'nsslapd-allow-unauthenticated-binds', + 'nsslapd-allow-anonymous-access' => 'nsslapd-allow-anonymous-access', 'nsslapd-saslpath' => 'nsslapd-saslpath', 'nsslapd-rundir' => 'nsslapd-rundir', 'nsslapd-schemadir' => 'nsslapd-schemadir', diff --git a/ldap/ldif/template-dse.ldif.in b/ldap/ldif/template-dse.ldif.in index 1dfd9d568..a0475386c 100644 --- a/ldap/ldif/template-dse.ldif.in +++ b/ldap/ldif/template-dse.ldif.in @@ -31,6 +31,7 @@ nsslapd-return-exact-case: on nsslapd-ssl-check-hostname: on nsslapd-allow-unauthenticated-binds: off nsslapd-require-secure-binds: off +nsslapd-allow-anonymous-access: on nsslapd-port: %ds_port% nsslapd-localuser: %ds_user% nsslapd-errorlog-logging-enabled: on diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index 359252f46..bf54d3cac 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -424,10 +424,19 @@ do_bind( Slapi_PBlock *pb ) /* accept null binds */ if (dn == NULL || *dn == '\0') { slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsAnonymousBinds); - /* by definition its anonymous is also UnAuthenticated so increment + /* by definition anonymous is also unauthenticated so increment that counter */ slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsUnAuthBinds); + /* Refuse the operation if anonymous access is disabled. */ + if (!config_get_anon_access_switch()) { + send_ldap_result(pb, LDAP_INAPPROPRIATE_AUTH, NULL, + "Anonymous access is not allowed", 0, NULL); + /* increment BindSecurityErrorcount */ + slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsBindSecurityErrors); + goto free_and_return; + } + /* call preop plugins */ if (plugin_call_plugins( pb, SLAPI_PLUGIN_PRE_BIND_FN ) == 0){ if ( auth_response_requested ) { @@ -444,6 +453,15 @@ do_bind( Slapi_PBlock *pb ) /* Increment unauthenticated bind counter */ slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsUnAuthBinds); + /* Refuse the operation if anonymous access is disabled. */ + if (!config_get_anon_access_switch()) { + send_ldap_result(pb, LDAP_INAPPROPRIATE_AUTH, NULL, + "Anonymous access is not allowed", 0, NULL); + /* increment BindSecurityErrorcount */ + slapi_counter_increment(g_get_global_snmp_vars()->ops_tbl.dsBindSecurityErrors); + goto free_and_return; + } + /* Refuse the operation if unauthenticated binds are disabled. */ if (!config_get_unauth_binds_switch()) { /* As stated in RFC 4513, a server SHOULD by default fail diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index 8b1e2e5a5..4dd81f974 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -480,8 +480,21 @@ connection_dispatch_operation(Connection *conn, Operation *op, Slapi_PBlock *pb) /* Copy the Connection DN into the operation struct */ op_copy_identity( conn, op ); - /* process the operation */ + /* If anonymous access is disabled and the connection is + * not authenticated, only allow the BIND operation. */ + if (!config_get_anon_access_switch() && (op->o_tag != LDAP_REQ_BIND) && + ((op->o_authtype == NULL) || (strcasecmp(op->o_authtype, SLAPD_AUTH_NONE) == 0))) { + slapi_log_access( LDAP_DEBUG_STATS, + "conn=%" NSPRIu64 " op=%d UNPROCESSED OPERATION\n", + conn->c_connid, op->o_opid ); + + send_ldap_result( pb, LDAP_INAPPROPRIATE_AUTH, NULL, + "Anonymous access is not allowed.", + 0, NULL ); + return; + } + /* process the operation */ switch ( op->o_tag ) { case LDAP_REQ_BIND: operation_set_type(op,SLAPI_OPERATION_BIND); diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 3d2035341..5eb1afd5a 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -609,7 +609,11 @@ static struct config_get_and_set { {CONFIG_REQUIRE_SECURE_BINDS_ATTRIBUTE, config_set_require_secure_binds, NULL, 0, (void**)&global_slapdFrontendConfig.require_secure_binds, CONFIG_ON_OFF, - (ConfigGetFunc)config_get_require_secure_binds} + (ConfigGetFunc)config_get_require_secure_binds}, + {CONFIG_ANON_ACCESS_ATTRIBUTE, config_set_anon_access_switch, + NULL, 0, + (void**)&global_slapdFrontendConfig.allow_anon_access, CONFIG_ON_OFF, + (ConfigGetFunc)config_get_anon_access_switch} #ifdef MEMPOOL_EXPERIMENTAL ,{CONFIG_MEMPOOL_SWITCH_ATTRIBUTE, config_set_mempool_switch, NULL, 0, @@ -861,6 +865,7 @@ FrontendConfig_init () { #endif cfg->allow_unauth_binds = LDAP_OFF; cfg->require_secure_binds = LDAP_OFF; + cfg->allow_anon_access = LDAP_ON; cfg->slapi_counters = LDAP_ON; cfg->threadnumber = SLAPD_DEFAULT_MAX_THREADS; cfg->maxthreadsperconn = SLAPD_DEFAULT_MAX_THREADS_PER_CONN; @@ -4557,7 +4562,19 @@ config_get_require_secure_binds(void) retVal = slapdFrontendConfig->require_secure_binds; CFG_UNLOCK_READ(slapdFrontendConfig); -return retVal; + return retVal; +} + +int +config_get_anon_access_switch(void) +{ + int retVal; + slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); + CFG_LOCK_READ(slapdFrontendConfig); + retVal = slapdFrontendConfig->allow_anon_access; + CFG_UNLOCK_READ(slapdFrontendConfig); + + return retVal; } int @@ -5336,6 +5353,22 @@ config_set_require_secure_binds( const char *attrname, char *value, return retVal; } +int +config_set_anon_access_switch( const char *attrname, char *value, + char *errorbuf, int apply ) +{ + int retVal = LDAP_SUCCESS; + slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig(); + + retVal = config_set_onoff(attrname, + value, + &(slapdFrontendConfig->allow_anon_access), + errorbuf, + apply); + + return retVal; +} + /* * This function is intended to be used from the dse code modify callback. It diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 4b1bbdf7b..c408f6906 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -344,6 +344,7 @@ int config_set_outbound_ldap_io_timeout( const char *attrname, char *value, char *errorbuf, int apply ); int config_set_unauth_binds_switch(const char *attrname, char *value, char *errorbuf, int apply ); int config_set_require_secure_binds(const char *attrname, char *value, char *errorbuf, int apply ); +int config_set_anon_access_switch(const char *attrname, char *value, char *errorbuf, int apply ); int config_set_accesslogbuffering(const char *attrname, char *value, char *errorbuf, int apply); int config_set_csnlogging(const char *attrname, char *value, char *errorbuf, int apply); @@ -473,6 +474,7 @@ int config_get_rewrite_rfc1274(); int config_get_outbound_ldap_io_timeout(void); int config_get_unauth_binds_switch(void); int config_get_require_secure_binds(void); +int config_get_anon_access_switch(void); int config_get_csnlogging(); #ifdef MEMPOOL_EXPERIMENTAL int config_get_mempool_switch(); diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index ceb46b2cb..ba65781c7 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1722,6 +1722,7 @@ typedef struct _slapdEntryPoints { #define CONFIG_SVRTAB_ATTRIBUTE "nsslapd-svrtab" #define CONFIG_UNAUTH_BINDS_ATTRIBUTE "nsslapd-allow-unauthenticated-binds" #define CONFIG_REQUIRE_SECURE_BINDS_ATTRIBUTE "nsslapd-require-secure-binds" +#define CONFIG_ANON_ACCESS_ATTRIBUTE "nsslapd-allow-anonymous-access" #ifndef _WIN32 #define CONFIG_LOCALUSER_ATTRIBUTE "nsslapd-localuser" #endif /* !_WIN32 */ @@ -2016,6 +2017,7 @@ typedef struct _slapdFrontendConfig { int slapi_counters; /* switch to turn slapi_counters on/off */ int allow_unauth_binds; /* switch to enable/disable unauthenticated binds */ int require_secure_binds; /* switch to require simple binds to use a secure channel */ + int allow_anon_access; /* switch to enable/disable anonymous access */ size_t maxsasliosize; /* limit incoming SASL IO packet size */ #ifndef _WIN32 struct passwd *localuserinfo; /* userinfo of localuser */ diff --git a/selinux/dirsrv.te b/selinux/dirsrv.te index b40459b9d..6dcabe1f1 100644 --- a/selinux/dirsrv.te +++ b/selinux/dirsrv.te @@ -86,7 +86,7 @@ allow dirsrv_t self:fifo_file { read write }; # process stuff allow dirsrv_t self:process { getsched setsched signal_perms}; -allow dirsrv_t self:capability { sys_nice setuid setgid chown dac_override }; +allow dirsrv_t self:capability { sys_nice setuid setgid chown dac_override fowner }; # semaphores allow dirsrv_t self:sem all_sem_perms;
0
1698dd8e89b8d11be94c547c194e7a455ffd42a0
389ds/389-ds-base
Issue 50071 - Set ports in local_simple_allocate function Description: remove_ds_instance function require DirSrv object having port and sslport defined for semanage remove label operation. We should set it in local_simple_allocate too. Fix DSEldif.get function so it returns a list instead of a view (Python 3 change). https://pagure.io/389-ds-base/issue/50071 Reviewed by: mhonek, tbordaz, cheimes (Thanks!)
commit 1698dd8e89b8d11be94c547c194e7a455ffd42a0 Author: Simon Pichugin <[email protected]> Date: Wed Dec 5 11:57:59 2018 +0100 Issue 50071 - Set ports in local_simple_allocate function Description: remove_ds_instance function require DirSrv object having port and sslport defined for semanage remove label operation. We should set it in local_simple_allocate too. Fix DSEldif.get function so it returns a list instead of a view (Python 3 change). https://pagure.io/389-ds-base/issue/50071 Reviewed by: mhonek, tbordaz, cheimes (Thanks!) diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index adeb512cb..ad09fc458 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -85,6 +85,7 @@ from lib389.utils import ( from lib389.paths import Paths from lib389.nss_ssl import NssSsl from lib389.tasks import BackupTask, RestoreTask +from lib389.dseldif import DSEldif # mixin # from lib389.tools import DirSrvTools @@ -431,8 +432,13 @@ class DirSrv(SimpleLDAPObject, object): # We must also alloc host and ports for some manipulation tasks self.host = socket.gethostname() - # self.port ... - # self.sslport ... + + dse_ldif = DSEldif(self) + port = dse_ldif.get(DN_CONFIG, "nsslapd-port", single=True) + sslport = dse_ldif.get(DN_CONFIG, "nsslapd-secureport", single=True) + + self.port = int(port) if port is not None else None + self.sslport = int(sslport) if sslport is not None else None self.binddn = binddn self.bindpw = password diff --git a/src/lib389/lib389/dseldif.py b/src/lib389/lib389/dseldif.py index 1e0de6c0e..719ba6be7 100644 --- a/src/lib389/lib389/dseldif.py +++ b/src/lib389/lib389/dseldif.py @@ -89,13 +89,10 @@ class DSEldif(object): except ValueError: return None + vals = list(attr_data.values()) if single: - vals = list(attr_data.values()) - if len(vals) > 0: - return vals[0] - else: - return None - return attr_data.values() + return vals[0] if len(vals) > 0 else None + return vals def add(self, entry_dn, attr, value): """Add an attribute under a given entry diff --git a/src/lib389/lib389/instance/remove.py b/src/lib389/lib389/instance/remove.py index 0245db714..21da083e7 100644 --- a/src/lib389/lib389/instance/remove.py +++ b/src/lib389/lib389/instance/remove.py @@ -78,7 +78,8 @@ def remove_ds_instance(dirsrv): subprocess.check_call(["systemctl", "disable", "dirsrv@{}".format(dirsrv.serverid)]) # Remove selinux port label - selinux_label_port(dirsrv.port, remove_label=True) + if dirsrv.port is not None: + selinux_label_port(dirsrv.port, remove_label=True) if dirsrv.sslport is not None: selinux_label_port(dirsrv.sslport, remove_label=True) diff --git a/src/lib389/lib389/tests/instance/remove_test.py b/src/lib389/lib389/tests/instance/remove_test.py index 444272664..0be7c8b86 100644 --- a/src/lib389/lib389/tests/instance/remove_test.py +++ b/src/lib389/lib389/tests/instance/remove_test.py @@ -9,12 +9,14 @@ import os import subprocess import pytest +import logging +from lib389 import DirSrv from lib389.instance.remove import remove_ds_instance from lib389._constants import ReplicaRole from lib389.topologies import create_topology [email protected](scope="module") [email protected](scope="function") def topology_st(request): """Create DS standalone instance""" @@ -28,11 +30,17 @@ def topology_st(request): return topology -def test_basic(topology_st): [email protected]("simple_allocate", (True, False)) +def test_basic(topology_st, simple_allocate): """Check that all DS directories and systemd items were removed""" inst = topology_st.standalone + # FreeIPA uses local_simple_allocate for the removal process + if simple_allocate: + inst = DirSrv(verbose=inst.verbose) + inst.local_simple_allocate(topology_st.standalone.serverid) + remove_ds_instance(inst) paths = [inst.ds_paths.backup_dir, @@ -51,3 +59,5 @@ def test_basic(topology_st): subprocess.check_output(['systemctl', 'is-enabled', 'dirsrv@{}'.format(inst.serverid)], encoding='utf-8') except subprocess.CalledProcessError as ex: assert "disabled" in ex.output + +
0
db699306809cfe74926e469a30eab9b6d68645bb
389ds/389-ds-base
Issue 5050 - bdb bulk op fails if fs page size > 8K (#5150)
commit db699306809cfe74926e469a30eab9b6d68645bb Author: progier389 <[email protected]> Date: Fri Feb 4 14:00:40 2022 +0100 Issue 5050 - bdb bulk op fails if fs page size > 8K (#5150) diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c index 02f11bb9e..a168ffb79 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_layer.c @@ -6586,6 +6586,13 @@ int bdb_public_cursor_bulkop(dbi_cursor_t *cursor, dbi_op_t op, dbi_val_t *key, if (bdb_cur == NULL) return DBI_RC_INVALID; + if (bulkdata->v.size < bdb_cur->dbp->pgsize) { + /* Make sure that size is 1024 aligned and >= db page size */ + long size = (bdb_cur->dbp->pgsize + 1023L) & ~1023L; + int flags = bulkdata->v.flags & (DBI_VF_BULK_DATA|DBI_VF_BULK_RECORD); + dblayer_bulk_set_buffer(bulkdata->be, bulkdata, slapi_ch_malloc(size), size, flags); + } + bdb_dbival2dbt(key, &bdb_key, PR_FALSE); bdb_dbival2dbt(&bulkdata->v, &bdb_data, PR_FALSE); switch (op)
0
d1932b9c9eae1d65a33a12e4cedd45d6370f6516
389ds/389-ds-base
Issue 5856 - SyntaxWarning: invalid escape sequence '\,' Bug Description: An error is logged during rpm build: /usr/lib/python3.12/site-packages/lib389/cli_conf/replication.py:1682: SyntaxWarning: invalid escape sequence '\,' Fix Description: Fix the typo. Fixes: https://github.com/389ds/389-ds-base/issues/5856 Reviewed-by: @droideck (Thanks!)
commit d1932b9c9eae1d65a33a12e4cedd45d6370f6516 Author: Viktor Ashirov <[email protected]> Date: Tue Jul 25 12:32:02 2023 +0200 Issue 5856 - SyntaxWarning: invalid escape sequence '\,' Bug Description: An error is logged during rpm build: /usr/lib/python3.12/site-packages/lib389/cli_conf/replication.py:1682: SyntaxWarning: invalid escape sequence '\,' Fix Description: Fix the typo. Fixes: https://github.com/389ds/389-ds-base/issues/5856 Reviewed-by: @droideck (Thanks!) diff --git a/src/lib389/lib389/cli_conf/replication.py b/src/lib389/lib389/cli_conf/replication.py index b6f9861c1..48a65a51e 100644 --- a/src/lib389/lib389/cli_conf/replication.py +++ b/src/lib389/lib389/cli_conf/replication.py @@ -1679,7 +1679,7 @@ def create_parser(subparsers): winsync_agmt_add_parser.add_argument('--sync-interval', help="Sets the interval that DS checks AD for changes in entries") winsync_agmt_add_parser.add_argument('--one-way-sync', help="Sets which direction to perform synchronization: \"toWindows\", or " - "\"fromWindows\,. By default sync occurs in both directions.") + "\"fromWindows\". By default sync occurs in both directions.") winsync_agmt_add_parser.add_argument('--move-action', help="Sets instructions on how to handle moved or deleted entries: " "\"none\", \"unsync\", or \"delete\"")
0
0d1ce9de608d582ea2ca0f5e48fe2f2213f0b683
389ds/389-ds-base
Add 'void' to function definition to avoid compiler warnings During compiling of FreeIPA we are receiving compiler error: slapi-plugin.h:6149, GNU C Compiler 4 (gcc), Priority: Normal function declaration isn't a prototype [-Wstrict-prototypes] This patch should fix the compiler warning. Reviewed by [email protected].
commit 0d1ce9de608d582ea2ca0f5e48fe2f2213f0b683 Author: Martin Basti <[email protected]> Date: Tue Nov 3 17:32:53 2015 +0100 Add 'void' to function definition to avoid compiler warnings During compiling of FreeIPA we are receiving compiler error: slapi-plugin.h:6149, GNU C Compiler 4 (gcc), Priority: Normal function declaration isn't a prototype [-Wstrict-prototypes] This patch should fix the compiler warning. Reviewed by [email protected]. diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index 72f3920fb..d2b076b45 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -6146,7 +6146,7 @@ int slapi_rwlock_unlock( Slapi_RWLock *rwlock ); * * \return the size of Slapi_RWLock */ -int slapi_rwlock_get_size(); +int slapi_rwlock_get_size( void ); /* * thread-safe LDAP connections diff --git a/ldap/servers/slapd/slapi2nspr.c b/ldap/servers/slapd/slapi2nspr.c index 4bd88fef6..1bfb3069b 100644 --- a/ldap/servers/slapd/slapi2nspr.c +++ b/ldap/servers/slapd/slapi2nspr.c @@ -261,7 +261,7 @@ slapi_rwlock_unlock( Slapi_RWLock *rwlock ) } int -slapi_rwlock_get_size() +slapi_rwlock_get_size( void ) { #ifdef USE_POSIX_RWLOCKS return sizeof(pthread_rwlock_t);
0
da90d57c30bf93265f06499b8ea2102378a0ed12
389ds/389-ds-base
Ticket 47965 - Fix coverity issues (2014/11/24) 12864 - nesting level adjustment - sync_presist.c 12867 - Uninitialized pointer read - repl5_replica.c 12870 - Unused value - repl5_ruv.c 12880, 12881, 12893 - Unused value - dblayer.c 12887 - nesting level adjustment - acl.c 12894 - nesting level adjustment - acl_ext.c 12898 - Logically dead code - acllas.c 12891 - Unused value - windows_inc_protocol.c 12902 - Unused value - repl5_inc_protocol.c https://fedorahosted.org/389/ticket/47965 Reviewed by: rmeggins(Thanks!)
commit da90d57c30bf93265f06499b8ea2102378a0ed12 Author: Mark Reynolds <[email protected]> Date: Mon Nov 24 12:22:34 2014 -0500 Ticket 47965 - Fix coverity issues (2014/11/24) 12864 - nesting level adjustment - sync_presist.c 12867 - Uninitialized pointer read - repl5_replica.c 12870 - Unused value - repl5_ruv.c 12880, 12881, 12893 - Unused value - dblayer.c 12887 - nesting level adjustment - acl.c 12894 - nesting level adjustment - acl_ext.c 12898 - Logically dead code - acllas.c 12891 - Unused value - windows_inc_protocol.c 12902 - Unused value - repl5_inc_protocol.c https://fedorahosted.org/389/ticket/47965 Reviewed by: rmeggins(Thanks!) diff --git a/ldap/servers/plugins/acl/acl.c b/ldap/servers/plugins/acl/acl.c index 403c5b3b5..f04e25816 100644 --- a/ldap/servers/plugins/acl/acl.c +++ b/ldap/servers/plugins/acl/acl.c @@ -2106,9 +2106,10 @@ acl__resource_match_aci( Acl_PBlock *aclpb, aci_t *aci, int skip_attrEval, int * ** acl in the entry cache list. */ if (!((res_right & (SLAPI_ACL_SEARCH | SLAPI_ACL_READ)) && - (aci_right & (SLAPI_ACL_SEARCH | SLAPI_ACL_READ)))) + (aci_right & (SLAPI_ACL_SEARCH | SLAPI_ACL_READ)))){ matches = ACL_FALSE; goto acl__resource_match_aci_EXIT; + } } diff --git a/ldap/servers/plugins/acl/acl_ext.c b/ldap/servers/plugins/acl/acl_ext.c index 126a23458..0863de022 100644 --- a/ldap/servers/plugins/acl/acl_ext.c +++ b/ldap/servers/plugins/acl/acl_ext.c @@ -334,12 +334,14 @@ acl_operation_ext_destructor ( void *ext, void *object, void *parent ) int attr_only = 0; PRLock *shared_lock = aclcb->aclcb_lock; - if (aclcb->aclcb_lock ) PR_Lock ( shared_lock ); + if (aclcb->aclcb_lock ) + PR_Lock ( shared_lock ); else { goto clean_aclpb; } if ( !aclcb->aclcb_lock ) { - slapi_log_error (SLAPI_LOG_FATAL, plugin_name, "aclcb lock released! aclcb cache can't be refreshed\n"); + slapi_log_error (SLAPI_LOG_FATAL, plugin_name, + "aclcb lock released! aclcb cache can't be refreshed\n"); PR_Unlock ( shared_lock ); goto clean_aclpb; } @@ -347,29 +349,29 @@ acl_operation_ext_destructor ( void *ext, void *object, void *parent ) /* We need to refresh the aclcb cache */ if ( aclpb->aclpb_state & ACLPB_UPD_ACLCB_CACHE ) acl_clean_aclEval_context ( &aclcb->aclcb_eval_context, 0 /* clean*/ ); - if ( aclpb->aclpb_prev_entryEval_context.acle_numof_attrs ) { - c_evalContext = &aclpb->aclpb_prev_entryEval_context; - } else { - c_evalContext = &aclpb->aclpb_curr_entryEval_context; - } - - if (( aclpb->aclpb_state & ACLPB_INCR_ACLCB_CACHE ) && - ! ( aclpb->aclpb_state & ACLPB_UPD_ACLCB_CACHE )) - attr_only = 1; - - acl_copyEval_context ( NULL, c_evalContext, &aclcb->aclcb_eval_context, attr_only ); - - aclcb->aclcb_aclsignature = aclpb->aclpb_signature; - if ( aclcb->aclcb_sdn && - (0 != slapi_sdn_compare ( aclcb->aclcb_sdn, - aclpb->aclpb_authorization_sdn ) ) ) { - slapi_sdn_set_ndn_byval( aclcb->aclcb_sdn, - slapi_sdn_get_ndn ( aclpb->aclpb_authorization_sdn ) ); - } - aclcb->aclcb_state = 0; - aclcb->aclcb_state |= ACLCB_HAS_CACHED_EVALCONTEXT; - - PR_Unlock ( shared_lock ); + if ( aclpb->aclpb_prev_entryEval_context.acle_numof_attrs ) { + c_evalContext = &aclpb->aclpb_prev_entryEval_context; + } else { + c_evalContext = &aclpb->aclpb_curr_entryEval_context; + } + + if (( aclpb->aclpb_state & ACLPB_INCR_ACLCB_CACHE ) && + ! ( aclpb->aclpb_state & ACLPB_UPD_ACLCB_CACHE )) + attr_only = 1; + + acl_copyEval_context ( NULL, c_evalContext, &aclcb->aclcb_eval_context, attr_only ); + + aclcb->aclcb_aclsignature = aclpb->aclpb_signature; + if ( aclcb->aclcb_sdn && + (0 != slapi_sdn_compare( aclcb->aclcb_sdn, aclpb->aclpb_authorization_sdn ))) + { + slapi_sdn_set_ndn_byval( aclcb->aclcb_sdn, + slapi_sdn_get_ndn ( aclpb->aclpb_authorization_sdn ) ); + } + aclcb->aclcb_state = 0; + aclcb->aclcb_state |= ACLCB_HAS_CACHED_EVALCONTEXT; + + PR_Unlock ( shared_lock ); } clean_aclpb: diff --git a/ldap/servers/plugins/acl/acllas.c b/ldap/servers/plugins/acl/acllas.c index 2d0dae97a..439c8f174 100644 --- a/ldap/servers/plugins/acl/acllas.c +++ b/ldap/servers/plugins/acl/acllas.c @@ -1726,10 +1726,6 @@ DS_LASAuthMethodEval(NSErr_t *errp, char *attr_name, CmpOp_t comparator, } else { rc = (matched == ACL_TRUE ? LAS_EVAL_FALSE : LAS_EVAL_TRUE); } - } else { - rc = LAS_EVAL_FAIL; - slapi_log_error( SLAPI_LOG_ACL, plugin_name, - "Returning UNDEFINED for authmethod evaluation.\n"); } return rc; diff --git a/ldap/servers/plugins/replication/repl5_inc_protocol.c b/ldap/servers/plugins/replication/repl5_inc_protocol.c index 3bb68e7e0..9f81c047a 100644 --- a/ldap/servers/plugins/replication/repl5_inc_protocol.c +++ b/ldap/servers/plugins/replication/repl5_inc_protocol.c @@ -922,7 +922,6 @@ repl5_inc_run(Private_Repl_Protocol *prp) /* Destroy the backoff timer, since we won't need it anymore */ backoff_delete(&prp_priv->backoff); } - use_busy_backoff_timer = PR_FALSE; } else if (event_occurred(prp, EVENT_TRIGGERING_CRITERIA_MET)){ /* changes are available */ if ( prp_priv->backoff == NULL || backoff_expired (prp_priv->backoff, 60)){ diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index dab1c4eb0..77663f65a 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -2140,7 +2140,7 @@ done: char *ridstr = NULL; char *token = NULL; char *repl_root; - char *iter; + char *iter = NULL; int i; for(i = 0; clean_vals[i]; i++){ diff --git a/ldap/servers/plugins/replication/repl5_ruv.c b/ldap/servers/plugins/replication/repl5_ruv.c index 500fd7a26..132c641ca 100644 --- a/ldap/servers/plugins/replication/repl5_ruv.c +++ b/ldap/servers/plugins/replication/repl5_ruv.c @@ -705,7 +705,6 @@ set_max_csn_nolock_ext(RUV *ruv, const CSN *max_csn, const char *replica_purl, P csn_as_string(replica->csn, PR_FALSE, csn2)); return_value = RUV_COVERS_CSN; } - return_value = RUV_SUCCESS; } return return_value; } diff --git a/ldap/servers/plugins/replication/windows_inc_protocol.c b/ldap/servers/plugins/replication/windows_inc_protocol.c index d62deecfb..ec6ca55a6 100644 --- a/ldap/servers/plugins/replication/windows_inc_protocol.c +++ b/ldap/servers/plugins/replication/windows_inc_protocol.c @@ -675,63 +675,64 @@ windows_inc_run(Private_Repl_Protocol *prp) backoff_delete(&prp_priv->backoff); } else if (event_occurred(prp, EVENT_BACKOFF_EXPIRED)) - { + { rc = windows_acquire_replica(prp, &ruv, 1 /* check RUV for incremental */); use_busy_backoff_timer = PR_FALSE; if (rc == ACQUIRE_SUCCESS) - { - next_state = STATE_SENDING_UPDATES; - } + { + next_state = STATE_SENDING_UPDATES; + } else if (rc == ACQUIRE_REPLICA_BUSY) - { - next_state = STATE_BACKOFF; - use_busy_backoff_timer = PR_TRUE; - } + { + next_state = STATE_BACKOFF; + use_busy_backoff_timer = PR_TRUE; + } else if (rc == ACQUIRE_CONSUMER_WAS_UPTODATE) - { + { next_state = STATE_WAIT_CHANGES; - } + } else if (rc == ACQUIRE_TRANSIENT_ERROR) - { - next_state = STATE_BACKOFF; - } + { + next_state = STATE_BACKOFF; + } else if (rc == ACQUIRE_FATAL_ERROR) - { - next_state = STATE_STOP_FATAL_ERROR; - } + { + next_state = STATE_STOP_FATAL_ERROR; + } + if (rc != ACQUIRE_SUCCESS) - { - int optype, ldaprc; - windows_conn_get_error(prp->conn, &optype, &ldaprc); - agmt_set_last_update_status(prp->agmt, ldaprc, + { + int optype, ldaprc; + windows_conn_get_error(prp->conn, &optype, &ldaprc); + agmt_set_last_update_status(prp->agmt, ldaprc, prp->last_acquire_response_code, NULL); - } - /* - * We either need to step the backoff timer, or - * destroy it if we don't need it anymore. - */ + } + + /* + * We either need to step the backoff timer, or + * destroy it if we don't need it anymore. + */ if (STATE_BACKOFF == next_state) - { - time_t next_fire_time; - time_t now; - /* Step the backoff timer */ - time(&now); - next_fire_time = backoff_step(prp_priv->backoff); - /* And go back to sleep */ - slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, - "%s: Replication session backing off for %ld seconds\n", - agmt_get_long_name(prp->agmt), - next_fire_time - now); + { + time_t next_fire_time; + time_t now; + /* Step the backoff timer */ + time(&now); + next_fire_time = backoff_step(prp_priv->backoff); + /* And go back to sleep */ + slapi_log_error(SLAPI_LOG_REPL, windows_repl_plugin_name, + "%s: Replication session backing off for %ld seconds\n", + agmt_get_long_name(prp->agmt), + next_fire_time - now); - protocol_sleep(prp, PR_INTERVAL_NO_TIMEOUT); - } + protocol_sleep(prp, PR_INTERVAL_NO_TIMEOUT); + } else - { - /* Destroy the backoff timer, since we won't need it anymore */ - backoff_delete(&prp_priv->backoff); - } - use_busy_backoff_timer = PR_FALSE; - } + { + /* Destroy the backoff timer, since we won't need it anymore */ + backoff_delete(&prp_priv->backoff); + } + } else if (event_occurred(prp, EVENT_TRIGGERING_CRITERIA_MET)) { /* changes are available */ diff --git a/ldap/servers/plugins/sync/sync_persist.c b/ldap/servers/plugins/sync/sync_persist.c index 8d4610272..f41a10c4a 100644 --- a/ldap/servers/plugins/sync/sync_persist.c +++ b/ldap/servers/plugins/sync/sync_persist.c @@ -661,10 +661,10 @@ sync_send_results( void *arg ) ectrls = (LDAPControl **)slapi_ch_calloc(2, sizeof (LDAPControl *)); if (req->req_cookie) sync_cookie_update(req->req_cookie, ec); - sync_create_state_control(ec, &ectrls[0], chg_type, req->req_cookie); - rc = slapi_send_ldap_search_entry( req->req_pblock, - ec, ectrls, - noattrs?noattrs:attrs, attrsonly ); + sync_create_state_control(ec, &ectrls[0], chg_type, req->req_cookie); + rc = slapi_send_ldap_search_entry( req->req_pblock, + ec, ectrls, + noattrs?noattrs:attrs, attrsonly ); if (rc) { slapi_log_error(SLAPI_LOG_CONNS, SYNC_PLUGIN_SUBSYSTEM, "Error %d sending entry %s\n", diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index f3159a9cd..252435564 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -4805,19 +4805,18 @@ static int checkpoint_threadmain(void *param) for (inst_obj = objset_first_obj(li->li_instance_set); inst_obj; - inst_obj = objset_next_obj(li->li_instance_set, inst_obj)) { + inst_obj = objset_next_obj(li->li_instance_set, inst_obj)) + { inst = (ldbm_instance *)object_get_data(inst_obj); rc = dblayer_get_id2entry(inst->inst_be, &db); - if (!db) { + if (!db || rc ) { continue; } LDAPDebug1Arg(LDAP_DEBUG_BACKLDBM, "compactdb: Compacting DB start: %s\n", inst->inst_name); rc = dblayer_txn_begin(inst->inst_be, NULL, &txn); if (rc) { - LDAPDebug1Arg(LDAP_DEBUG_ANY, - "compactdb: transaction begin failed: %d\n", - rc); + LDAPDebug1Arg(LDAP_DEBUG_ANY, "compactdb: transaction begin failed: %d\n", rc); break; } rc = db->compact(db, txn.back_txn_txn, NULL/*start*/, NULL/*stop*/, @@ -4826,12 +4825,20 @@ static int checkpoint_threadmain(void *param) LDAPDebug(LDAP_DEBUG_ANY, "compactdb: failed to compact %s; db error - %d %s\n", inst->inst_name, rc, db_strerror(rc)); - rc = dblayer_txn_abort(inst->inst_be, &txn); + if((rc = dblayer_txn_abort(inst->inst_be, &txn))){ + LDAPDebug(LDAP_DEBUG_ANY, "compactdb: failed to abort txn (%s) db error - %d %s\n", + inst->inst_name, rc, db_strerror(rc)); + break; + } } else { LDAPDebug2Args(LDAP_DEBUG_BACKLDBM, "compactdb: compact %s - %d pages freed\n", inst->inst_name, c_data.compact_pages_free); - rc = dblayer_txn_commit(inst->inst_be, &txn); + if((rc = dblayer_txn_commit(inst->inst_be, &txn))){ + LDAPDebug(LDAP_DEBUG_ANY, "compactdb: failed to commit txn (%s) db error - %d %s\n", + inst->inst_name, rc, db_strerror(rc)); + break; + } } } time_of_last_comapctdb_completion = current_time(); /* seconds since epoch */ diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index 7f806126a..3cb40fccf 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -2024,28 +2024,33 @@ slapi_pwpolicy_make_response_control (Slapi_PBlock *pb, int seconds, int logins, } rc = ber_printf( ber, "{" ); - if ( seconds >= 0 || logins >= 0 ) { - if ( seconds >= 0 ) { - rc = ber_printf( ber, "t{ti}", LDAP_TAG_PWP_WARNING, - LDAP_TAG_PWP_SECSLEFT, - seconds ); - } - else { - rc = ber_printf( ber, "t{ti}", LDAP_TAG_PWP_WARNING, - LDAP_TAG_PWP_GRCLOGINS, - logins ); + if ( rc != -1){ + if(seconds >= 0 || logins >= 0 ) { + if ( seconds >= 0 ) { + rc = ber_printf( ber, "t{ti}", LDAP_TAG_PWP_WARNING, + LDAP_TAG_PWP_SECSLEFT, + seconds ); + } + else { + rc = ber_printf( ber, "t{ti}", LDAP_TAG_PWP_WARNING, + LDAP_TAG_PWP_GRCLOGINS, + logins ); + } + } + if (rc != -1){ + if ( error >= 0 ) { + rc = ber_printf( ber, "te", LDAP_TAG_PWP_ERROR, error ); + } + if (rc != -1){ + rc = ber_printf( ber, "}" ); + if ( rc != -1 ) + { + rc = ber_flatten( ber, &bvp ); + } + } } } - if ( error >= 0 ) { - rc = ber_printf( ber, "te", LDAP_TAG_PWP_ERROR, error ); - } - rc = ber_printf( ber, "}" ); - if ( rc != -1 ) - { - rc = ber_flatten( ber, &bvp ); - } - ber_free( ber, 1 ); if ( rc != -1 ) @@ -2054,11 +2059,11 @@ slapi_pwpolicy_make_response_control (Slapi_PBlock *pb, int seconds, int logins, new_ctrl.ldctl_oid = LDAP_X_CONTROL_PWPOLICY_RESPONSE; new_ctrl.ldctl_value = *bvp; new_ctrl.ldctl_iscritical = 0; - rc= slapi_pblock_set( pb, SLAPI_ADD_RESCONTROL, &new_ctrl ); + rc = slapi_pblock_set( pb, SLAPI_ADD_RESCONTROL, &new_ctrl ); ber_bvfree(bvp); } - LDAPDebug( LDAP_DEBUG_TRACE, "<= slapi_pwpolicy_make_response_control", 0, 0, 0 ); + LDAPDebug( LDAP_DEBUG_TRACE, "<= slapi_pwpolicy_make_response_control (%d)", rc, 0, 0 ); return (rc==-1?LDAP_OPERATIONS_ERROR:LDAP_SUCCESS); }
0
96c130b432ce0b15028e325c0e337679291aef9f
389ds/389-ds-base
Ticket #47960 - cookie_change_info returns random negative number if there was no change in a tree Description: An additional fix for the type mismatch for the change numbers. Change Number is declared as "unsigned long" in the Retro Changelog plugin, while cookie_change_info in the Content Sync plugin is "int", which could end up with a negative number when the change number passes (2^31 - 1). Changing the type of cookie_change_info to "unsigned long". https://fedorahosted.org/389/ticket/47960 Reviewed by [email protected] and [email protected] (Thank you, Rich and Thierry!!)
commit 96c130b432ce0b15028e325c0e337679291aef9f Author: Noriko Hosoi <[email protected]> Date: Fri Dec 12 15:41:36 2014 -0800 Ticket #47960 - cookie_change_info returns random negative number if there was no change in a tree Description: An additional fix for the type mismatch for the change numbers. Change Number is declared as "unsigned long" in the Retro Changelog plugin, while cookie_change_info in the Content Sync plugin is "int", which could end up with a negative number when the change number passes (2^31 - 1). Changing the type of cookie_change_info to "unsigned long". https://fedorahosted.org/389/ticket/47960 Reviewed by [email protected] and [email protected] (Thank you, Rich and Thierry!!) diff --git a/ldap/servers/plugins/sync/sync.h b/ldap/servers/plugins/sync/sync.h index 0bcec7a72..803c656a0 100644 --- a/ldap/servers/plugins/sync/sync.h +++ b/ldap/servers/plugins/sync/sync.h @@ -64,10 +64,12 @@ #define CL_ATTR_NEWSUPERIOR "newsuperior" #define CL_SRCH_BASE "cn=changelog" +#define SYNC_INVALID_CHANGENUM ((unsigned long)-1) + typedef struct sync_cookie { char *cookie_client_signature; char *cookie_server_signature; - int cookie_change_info; + unsigned long cookie_change_info; } Sync_Cookie; typedef struct sync_update { @@ -80,8 +82,8 @@ typedef struct sync_update { typedef struct sync_callback { Slapi_PBlock *orig_pb; - int changenr; - int change_start; + unsigned long changenr; + unsigned long change_start; int cb_err; Sync_UpdateNode *cb_updates; } Sync_CallBackData; @@ -112,6 +114,7 @@ int sync_cookie_isvalid (Sync_Cookie *testcookie, Sync_Cookie *refcookie); void sync_cookie_free (Sync_Cookie **freecookie); char * sync_cookie2str(Sync_Cookie *cookie); int sync_number2int(char *nrstr); +unsigned long sync_number2ulong(char *nrstr); char *sync_nsuniqueid2uuid(const char *nsuniqueid); int sync_is_active (Slapi_Entry *e, Slapi_PBlock *pb); diff --git a/ldap/servers/plugins/sync/sync_refresh.c b/ldap/servers/plugins/sync/sync_refresh.c index 4e256e6e2..bfff77b7b 100644 --- a/ldap/servers/plugins/sync/sync_refresh.c +++ b/ldap/servers/plugins/sync/sync_refresh.c @@ -293,9 +293,9 @@ sync_refresh_update_content(Slapi_PBlock *pb, Sync_Cookie *client_cookie, Sync_C cb_data.orig_pb = pb; cb_data.change_start = client_cookie->cookie_change_info; - filter = slapi_ch_smprintf("(&(changenumber>=%d)(changenumber<=%d))", - client_cookie->cookie_change_info, - server_cookie->cookie_change_info); + filter = slapi_ch_smprintf("(&(changenumber>=%lu)(changenumber<=%lu))", + client_cookie->cookie_change_info, + server_cookie->cookie_change_info); slapi_search_internal_set_pb( seq_pb, CL_SRCH_BASE, @@ -305,7 +305,7 @@ sync_refresh_update_content(Slapi_PBlock *pb, Sync_Cookie *client_cookie, Sync_C 0, NULL, NULL, plugin_get_default_component_id(), - 0); + 0); rc = slapi_search_internal_callback_pb ( seq_pb, &cb_data, NULL, sync_read_entry_from_changelog, NULL); @@ -460,6 +460,7 @@ sync_read_entry_from_changelog( Slapi_Entry *cl_entry, void *cb_data) int chg_req; int prev = 0; int index = 0; + unsigned long chgnum = 0; Sync_CallBackData *cb = (Sync_CallBackData *) cb_data; if (cb == NULL) { @@ -470,13 +471,28 @@ sync_read_entry_from_changelog( Slapi_Entry *cl_entry, void *cb_data) if (uniqueid == NULL) { slapi_log_error (SLAPI_LOG_FATAL, SYNC_PLUGIN_SUBSYSTEM, "Retro Changelog does not provied nsuniquedid." - "Check RCL plugin configuration." ); + "Check RCL plugin configuration.\n" ); return(1); } - chgtype = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_CHGTYPE); chgnr = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_CHANGENUMBER); - - index = sync_number2int(chgnr) - cb->change_start; + chgnum = sync_number2ulong(chgnr); + if (SYNC_INVALID_CHANGENUM == chgnum) { + slapi_log_error (SLAPI_LOG_FATAL, SYNC_PLUGIN_SUBSYSTEM, + "Change number provided by Retro Changelog is invalid: %s\n", chgnr); + slapi_ch_free_string(&chgnr); + slapi_ch_free_string(&uniqueid); + return(1); + } + if (chgnum < cb->change_start) { + slapi_log_error (SLAPI_LOG_FATAL, SYNC_PLUGIN_SUBSYSTEM, + "Change number provided by Retro Changelog %s is less than the initial number %lu\n", + chgnr, cb->change_start); + slapi_ch_free_string(&chgnr); + slapi_ch_free_string(&uniqueid); + return(1); + } + index = chgnum - cb->change_start; + chgtype = sync_get_attr_value_from_entry (cl_entry, CL_ATTR_CHGTYPE); chg_req = sync_str2chgreq(chgtype); switch (chg_req){ case LDAP_REQ_ADD: diff --git a/ldap/servers/plugins/sync/sync_util.c b/ldap/servers/plugins/sync/sync_util.c index af22bcbda..67cb453b8 100644 --- a/ldap/servers/plugins/sync/sync_util.c +++ b/ldap/servers/plugins/sync/sync_util.c @@ -266,10 +266,10 @@ sync_cookie2str(Sync_Cookie *cookie) char *cookiestr = NULL; if (cookie) { - cookiestr = slapi_ch_smprintf("%s#%s#%d", - cookie->cookie_server_signature, - cookie->cookie_client_signature, - cookie->cookie_change_info); + cookiestr = slapi_ch_smprintf("%s#%s#%lu", + cookie->cookie_server_signature, + cookie->cookie_client_signature, + cookie->cookie_change_info); } return(cookiestr); } @@ -370,10 +370,11 @@ sync_handle_cnum_entry(Slapi_Entry *e, void *cb_data) slapi_attr_first_value( chattr,&sval ); if ( NULL != sval ) { value = slapi_value_get_berval ( sval ); - if( NULL != value && NULL != value->bv_val && - '\0' != value->bv_val[0]) { - cb->changenr = sync_number2int(value->bv_val); - cb->cb_err = 0; /* changenr successfully set */ + if (value && value->bv_val && ('\0' != value->bv_val[0])) { + cb->changenr = sync_number2ulong(value->bv_val); + if (SYNC_INVALID_CHANGENUM != cb->changenr) { + cb->cb_err = 0; /* changenr successfully set */ + } } } } @@ -452,31 +453,30 @@ sync_cookie_get_client_info(Slapi_PBlock *pb) clientinfo = slapi_ch_smprintf("%s:%s:%s",clientdn,targetdn,strfilter); return (clientinfo); } -static int +static unsigned long sync_cookie_get_change_number(int lastnr, const char *uniqueid) { Slapi_PBlock *srch_pb; Slapi_Entry **entries; Slapi_Entry *cl_entry; int rv; - int newnr = -1; + unsigned long newnr = SYNC_INVALID_CHANGENUM; char *filter = slapi_ch_smprintf("(&(changenumber>=%d)(targetuniqueid=%s))",lastnr,uniqueid); srch_pb = slapi_pblock_new(); - slapi_search_internal_set_pb(srch_pb, CL_SRCH_BASE, - LDAP_SCOPE_SUBTREE, filter, - NULL, 0, NULL, NULL, plugin_get_default_component_id(), 0); - slapi_search_internal_pb(srch_pb); + slapi_search_internal_set_pb(srch_pb, CL_SRCH_BASE, LDAP_SCOPE_SUBTREE, filter, + NULL, 0, NULL, NULL, plugin_get_default_component_id(), 0); + slapi_search_internal_pb(srch_pb); slapi_pblock_get(srch_pb, SLAPI_PLUGIN_INTOP_RESULT, &rv); - if ( rv == LDAP_SUCCESS) { + if (rv == LDAP_SUCCESS) { slapi_pblock_get(srch_pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &entries); - if (entries && *entries) { + if (entries && *entries) { Slapi_Attr *attr; Slapi_Value *val; cl_entry = *entries; /* only use teh first one */ slapi_entry_attr_find(cl_entry, CL_ATTR_CHANGENUMBER, &attr); slapi_attr_first_value(attr, &val); - newnr = sync_number2int((char *)slapi_value_get_string(val)); + newnr = sync_number2ulong((char *)slapi_value_get_string(val)); } } @@ -579,8 +579,8 @@ sync_cookie_parse (char *cookie) if (p) { *p = '\0'; sc->cookie_client_signature = slapi_ch_strdup(q); - sc->cookie_change_info = sync_number2int(p+1); - if (sc->cookie_change_info < 0) { + sc->cookie_change_info = sync_number2ulong(p+1); + if (SYNC_INVALID_CHANGENUM == sc->cookie_change_info) { goto error_return; } } else { @@ -716,14 +716,28 @@ sync_pblock_copy(Slapi_PBlock *src) return dest; } -int sync_number2int(char *chgnrstr) +int +sync_number2int(char *chgnrstr) { char *end; int nr; - nr = strtoul(chgnrstr, &end, 10); + nr = (int)strtoul(chgnrstr, &end, 10); if ( *end == '\0') { return (nr); } else { return (-1); } } + +unsigned long +sync_number2ulong(char *chgnrstr) +{ + char *end; + unsigned long nr; + nr = strtoul(chgnrstr, &end, 10); + if ( *end == '\0') { + return (nr); + } else { + return SYNC_INVALID_CHANGENUM; + } +}
0
a85e68002e75cc4f1208b9c6d55219667a21d798
389ds/389-ds-base
Bug 611790 - fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 https://bugzilla.redhat.com/show_bug.cgi?id=611790 Resolves: bug 611790 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 Fix description: Catch possible NULL pointer in windows_search_entry_ext().
commit a85e68002e75cc4f1208b9c6d55219667a21d798 Author: Endi S. Dewata <[email protected]> Date: Wed Jul 7 15:20:22 2010 -0500 Bug 611790 - fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 https://bugzilla.redhat.com/show_bug.cgi?id=611790 Resolves: bug 611790 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11940 - 12166 Fix description: Catch possible NULL pointer in windows_search_entry_ext(). diff --git a/ldap/servers/plugins/replication/windows_connection.c b/ldap/servers/plugins/replication/windows_connection.c index 5eab68d58..f337b944d 100644 --- a/ldap/servers/plugins/replication/windows_connection.c +++ b/ldap/servers/plugins/replication/windows_connection.c @@ -626,6 +626,12 @@ windows_search_entry_ext(Repl_Connection *conn, char* searchbase, char *filter, LDAPDebug( LDAP_DEBUG_TRACE, "=> windows_search_entry\n", 0, 0, 0 ); + if (!entry) { + LDAPDebug( LDAP_DEBUG_ANY, "windows_search_entry: NULL entry\n", 0, 0, 0 ); + return_value = CONN_LOCAL_ERROR; /* entry should never == NULL here */ + goto done; + } + *entry = NULL; if (windows_conn_connected(conn)) @@ -702,6 +708,7 @@ windows_search_entry_ext(Repl_Connection *conn, char* searchbase, char *filter, { return_value = CONN_NOT_CONNECTED; } +done: LDAPDebug( LDAP_DEBUG_TRACE, "<= windows_search_entry\n", 0, 0, 0 ); return return_value; }
0
1f95b57fb8b03f72c7d2a2ce5b14eed5ba320407
389ds/389-ds-base
Issue 6061 - Certificate lifetime displayed as NaN Bug Description: HOST_TIME_GMT is filled whith an unparsable format. Fix Description: Using `date -Iminutes` the format is compliant with "date time string format". Ensuring Date.parse() will always recognize it with right TZ. Author: Adadov Fixes: https://github.com/389ds/389-ds-base/issues/6061 Reviewed by: @vashirov, @progier389
commit 1f95b57fb8b03f72c7d2a2ce5b14eed5ba320407 Author: David Olivier <[email protected]> Date: Sun Oct 15 19:52:53 2023 +0200 Issue 6061 - Certificate lifetime displayed as NaN Bug Description: HOST_TIME_GMT is filled whith an unparsable format. Fix Description: Using `date -Iminutes` the format is compliant with "date time string format". Ensuring Date.parse() will always recognize it with right TZ. Author: Adadov Fixes: https://github.com/389ds/389-ds-base/issues/6061 Reviewed by: @vashirov, @progier389 diff --git a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx index 5ebca397c..fc9c898fa 100644 --- a/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx +++ b/src/cockpit/389-console/src/lib/ldap_editor/lib/utils.jsx @@ -998,7 +998,7 @@ export function showCertificate (certificate, showCertCallback) { 'echo ' + certificate + ' | base64 --decode | openssl x509 -inform DER -noout -subject -issuer -dates -serial ;' + // ' echo HOST_TIME_GMT=`TZ=GMT date "+%Y-%m-%d %H:%M:%S %Z"` ' // Issue with Firefox and Safari. - ' echo HOST_TIME_GMT=`TZ=GMT date`' + ' echo HOST_TIME_GMT=`date -Iminutes`' ]; let result = {};
0
3593eac1b751124811f1ca001240a46125b4e746
389ds/389-ds-base
Ticket 48820 - Clitool rename Bug Description: Clean up the clitools, as we use some of them in this feature https://fedorahosted.org/389/ticket/48820 Author: wibrown Review by: spichugi (Thanks!)
commit 3593eac1b751124811f1ca001240a46125b4e746 Author: William Brown <[email protected]> Date: Thu May 26 14:23:26 2016 +1000 Ticket 48820 - Clitool rename Bug Description: Clean up the clitools, as we use some of them in this feature https://fedorahosted.org/389/ticket/48820 Author: wibrown Review by: spichugi (Thanks!) diff --git a/src/lib389/lib389/clitools/__init__.py b/src/lib389/lib389/clitools/__init__.py old mode 100644 new mode 100755 index f12bdc2bc..cd66ce13b --- a/src/lib389/lib389/clitools/__init__.py +++ b/src/lib389/lib389/clitools/__init__.py @@ -40,7 +40,6 @@ class CliTool(object): binddn = self.args.binddn # There is a dict get key thing somewhere ... if self.inst.get(SER_ROOT_PW, None) is None: - print("") prompt_txt = ('Enter password for %s on instance %s: ' % (binddn, self.inst[SER_SERVERID_PROP])) @@ -56,7 +55,6 @@ class CliTool(object): if not self.ds.can_autobind(): self.get_rootdn_pass() self.ds.allocate(self.inst) - print("") self.ds.open() def disconnect(self): diff --git a/src/lib389/lib389/clitools/ds_aci_lint.py b/src/lib389/lib389/clitools/ds_aci_lint old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_aci_lint.py rename to src/lib389/lib389/clitools/ds_aci_lint diff --git a/src/lib389/lib389/clitools/ds_backend_getattr b/src/lib389/lib389/clitools/ds_backend_getattr new file mode 100755 index 000000000..cb8928ba5 --- /dev/null +++ b/src/lib389/lib389/clitools/ds_backend_getattr @@ -0,0 +1,42 @@ +#!/usr/bin/python + +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +# from clitools import clitools_parser, get_instance_dict, get_rootdn_pass +from lib389.clitools import CliTool, clitools_parser +# from lib389 import DirSrv +from lib389._constants import * +from argparse import ArgumentParser + +from lib389.backend import Backends + +class BackendTool(CliTool): + def backend_backend_list(self): + try: + self.populate_instance_dict(self.args.instance) + self.connect() + # This is pretty rough, it just dumps the objects + be = Backends(instance=self.ds).get(self.args.backend) + for attr in self.args.attributes: + print("%s : %s" % (attr, be.get(attr) )) + + finally: + self.disconnect() + +if __name__ == '__main__': + # Do some arg parse stuff + # You can always add a child parser here too ... + parser = clitools_parser.add_argument_group('monitor', 'monitoring options') + parser.add_argument('-n', '--backend', help='The name of the backend to ' + + ' retrieve monitoring information for.', required=True) + parser.add_argument('attributes', metavar='attr', type=str, nargs="+", + help='A list of attributes to retrieve') + args = clitools_parser.parse_args() + backendtool = BackendTool(args) + backendtool.backend_backend_list() diff --git a/src/lib389/lib389/clitools/ds_backend_list b/src/lib389/lib389/clitools/ds_backend_list new file mode 100755 index 000000000..67c8b31f4 --- /dev/null +++ b/src/lib389/lib389/clitools/ds_backend_list @@ -0,0 +1,39 @@ +#!/usr/bin/python + +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +# from clitools import clitools_parser, get_instance_dict, get_rootdn_pass +from lib389.clitools import CliTool, clitools_parser +# from lib389 import DirSrv +from lib389._constants import * +from argparse import ArgumentParser + +from lib389.backend import Backends + + +class BackendTool(CliTool): + def backend_backend_list(self): + try: + self.populate_instance_dict(self.args.instance) + self.connect() + # This is pretty rough, it just dumps the objects + backends = Backends(instance=self.ds) + for be in backends.list(): + print("backend: %s" % be) + + finally: + self.disconnect() + +if __name__ == '__main__': + # Do some arg parse stuff + # You can always add a child parser here too ... + parser = clitools_parser.add_argument_group('monitor', 'monitoring options') + args = clitools_parser.parse_args() + backendtool = BackendTool(args) + backendtool.backend_backend_list() diff --git a/src/lib389/lib389/clitools/ds_backend_setattr b/src/lib389/lib389/clitools/ds_backend_setattr new file mode 100755 index 000000000..5706ed3f0 --- /dev/null +++ b/src/lib389/lib389/clitools/ds_backend_setattr @@ -0,0 +1,43 @@ +#!/usr/bin/python + +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2016 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +# from clitools import clitools_parser, get_instance_dict, get_rootdn_pass +from lib389.clitools import CliTool, clitools_parser +# from lib389 import DirSrv +from lib389._constants import * +from argparse import ArgumentParser + + +class BackendTool(CliTool): + def backend_set_attr(self): + try: + self.populate_instance_dict(self.args.instance) + self.connect() + # This is pretty rough, it just dumps the objects + props = self.ds.backend.setProperties(bename=self.args.backend, prop=self.args.attribute[0], values=self.args.values) + print(props) + + finally: + self.disconnect() + +if __name__ == '__main__': + # Do some arg parse stuff + # You can always add a child parser here too ... + parser = clitools_parser.add_argument_group('monitor', 'monitoring options') + parser.add_argument('-n', '--backend', help='The name of the backend to ' + + ' retrieve monitoring information for.', required=True) + parser.add_argument('attribute', metavar='attr', type=str, nargs=1, + help='The attribute we wish to change') + parser.add_argument('values', metavar='values', type=str, nargs='+', + help='The values to apply to the attribute') + + args = clitools_parser.parse_args() + backendtool = BackendTool(args) + backendtool.backend_set_attr() diff --git a/src/lib389/lib389/clitools/krb_create_keytab.py b/src/lib389/lib389/clitools/ds_krb_create_keytab old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/krb_create_keytab.py rename to src/lib389/lib389/clitools/ds_krb_create_keytab diff --git a/src/lib389/lib389/clitools/krb_create_principal.py b/src/lib389/lib389/clitools/ds_krb_create_principal old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/krb_create_principal.py rename to src/lib389/lib389/clitools/ds_krb_create_principal diff --git a/src/lib389/lib389/clitools/krb_create_realm.py b/src/lib389/lib389/clitools/ds_krb_create_realm old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/krb_create_realm.py rename to src/lib389/lib389/clitools/ds_krb_create_realm diff --git a/src/lib389/lib389/clitools/krb_destroy_realm.py b/src/lib389/lib389/clitools/ds_krb_destroy_realm old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/krb_destroy_realm.py rename to src/lib389/lib389/clitools/ds_krb_destroy_realm diff --git a/src/lib389/lib389/clitools/ds_list_instances.py b/src/lib389/lib389/clitools/ds_list_instances old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_list_instances.py rename to src/lib389/lib389/clitools/ds_list_instances diff --git a/src/lib389/lib389/clitools/ds_monitor_backend.py b/src/lib389/lib389/clitools/ds_monitor_backend old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_monitor_backend.py rename to src/lib389/lib389/clitools/ds_monitor_backend diff --git a/src/lib389/lib389/clitools/ds_monitor_server.py b/src/lib389/lib389/clitools/ds_monitor_server old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_monitor_server.py rename to src/lib389/lib389/clitools/ds_monitor_server diff --git a/src/lib389/lib389/clitools/ds_schema_attributetype_list.py b/src/lib389/lib389/clitools/ds_schema_attributetype_list old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_schema_attributetype_list.py rename to src/lib389/lib389/clitools/ds_schema_attributetype_list diff --git a/src/lib389/lib389/clitools/ds_schema_attributetype_query.py b/src/lib389/lib389/clitools/ds_schema_attributetype_query old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_schema_attributetype_query.py rename to src/lib389/lib389/clitools/ds_schema_attributetype_query diff --git a/src/lib389/lib389/clitools/ds_start.py b/src/lib389/lib389/clitools/ds_start old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_start.py rename to src/lib389/lib389/clitools/ds_start diff --git a/src/lib389/lib389/clitools/ds_stop.py b/src/lib389/lib389/clitools/ds_stop old mode 100644 new mode 100755 similarity index 100% rename from src/lib389/lib389/clitools/ds_stop.py rename to src/lib389/lib389/clitools/ds_stop diff --git a/src/lib389/setup.py b/src/lib389/setup.py index 1c8a3129b..1c881a12c 100644 --- a/src/lib389/setup.py +++ b/src/lib389/setup.py @@ -48,5 +48,28 @@ setup( keywords='389 directory server test configure', packages=find_packages(exclude=['tests*']), - install_requires=['python-ldap'], + + # find lib389/clitools -name ds\* -exec echo \''{}'\', \; + data_files=[ + ('/usr/sbin/', [ + # 'lib389/clitools/ds_setup', + 'lib389/clitools/ds_aci_lint', + 'lib389/clitools/ds_list_instances', + 'lib389/clitools/ds_monitor_backend', + 'lib389/clitools/ds_monitor_server', + 'lib389/clitools/ds_schema_attributetype_list', + 'lib389/clitools/ds_schema_attributetype_query', + 'lib389/clitools/ds_start', + 'lib389/clitools/ds_stop', + 'lib389/clitools/ds_krb_create_keytab', + 'lib389/clitools/ds_krb_create_principal', + 'lib389/clitools/ds_krb_create_realm', + 'lib389/clitools/ds_krb_destroy_realm', + 'lib389/clitools/ds_backend_getattr', + 'lib389/clitools/ds_backend_setattr', + 'lib389/clitools/ds_backend_list', + ]), + ], + + install_requires=['python-ldap', 'dateutil'], )
0
f034f2bda3d4ecfaa2fb2f1dda0207c91064d9b9
389ds/389-ds-base
Ticket #533 - only scan for attributes to decrypt if there are encrypted attrs configured Bug description: When an internal entry is created in id2entry, all attributes are scanned in attrcrypt_decrypt_entry() and checked if they need to be decrypted regardless of SSL configured on the server or not. Fix description: In attrcrypt_encrypt_* and attrcrypt_decrypt_* functions, this patch checks the attrcrypt_configured flag. It goes scanning the attribute list only when the encrypt_ configured flag is set to true. Reviewed by Mark (Thank you!!)
commit f034f2bda3d4ecfaa2fb2f1dda0207c91064d9b9 Author: Noriko Hosoi <[email protected]> Date: Fri Jan 25 17:18:03 2013 -0800 Ticket #533 - only scan for attributes to decrypt if there are encrypted attrs configured Bug description: When an internal entry is created in id2entry, all attributes are scanned in attrcrypt_decrypt_entry() and checked if they need to be decrypted regardless of SSL configured on the server or not. Fix description: In attrcrypt_encrypt_* and attrcrypt_decrypt_* functions, this patch checks the attrcrypt_configured flag. It goes scanning the attribute list only when the encrypt_ configured flag is set to true. Reviewed by Mark (Thank you!!) diff --git a/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c b/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c index f0ef6923c..4e0278537 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_attrcrypt.c @@ -818,6 +818,15 @@ attrcrypt_decrypt_entry(backend *be, struct backentry *e) int rc = 0; Slapi_Attr *attr = NULL; char *type = NULL; + ldbm_instance *inst = (ldbm_instance *)be->be_instance_info; + + if (!inst->attrcrypt_configured) { + /* + * No encryption is enabled in this backend at all. + * There's no need to scan the attributes to decrypt them. + */ + return ret; + } LDAPDebug(LDAP_DEBUG_TRACE,"-> attrcrypt_decrypt_entry\n", 0, 0, 0); /* Scan through the entry's attributes, looking to see if any are configured for crypto */ @@ -870,6 +879,15 @@ attrcrypt_encrypt_entry_inplace(backend *be, const struct backentry *inout) char *type = NULL; Slapi_Attr *attr = NULL; Slapi_Value **svals = NULL; + ldbm_instance *inst = (ldbm_instance *)be->be_instance_info; + + if (!inst->attrcrypt_configured) { + /* + * No encryption is enabled in this backend at all. + * There's no need to scan the attributes to encrypt them. + */ + return ret; + } LDAPDebug(LDAP_DEBUG_TRACE,"-> attrcrypt_encrypt_entry_inplace\n", 0, 0, 0); /* Scan the entry's attributes looking for any that are configured for encryption */ @@ -906,6 +924,15 @@ attrcrypt_encrypt_entry(backend *be, const struct backentry *in, struct backentr struct backentry *new_entry = NULL; char *type = NULL; Slapi_Attr *attr = NULL; + ldbm_instance *inst = (ldbm_instance *)be->be_instance_info; + + if (!inst->attrcrypt_configured) { + /* + * No encryption is enabled in this backend at all. + * There's no need to scan the attributes to encrypt them. + */ + return ret; + } LDAPDebug(LDAP_DEBUG_TRACE,"-> attrcrypt_encrypt_entry\n", 0, 0, 0); *out = NULL; @@ -959,6 +986,12 @@ attrcrypt_encrypt_index_key(backend *be, struct attrinfo *ai, const struct berva char *out_data = NULL; size_t out_size = 0; struct berval *out_berval = NULL; + ldbm_instance *inst = (ldbm_instance *)be->be_instance_info; + + if (!inst->attrcrypt_configured) { + /* No encryption is enabled in this backend at all. */ + return ret; + } if (ai->ai_attrcrypt) { LDAPDebug(LDAP_DEBUG_TRACE,"-> attrcrypt_encrypt_index_key\n", 0, 0, 0); @@ -990,6 +1023,12 @@ attrcrypt_decrypt_index_key(backend *be, struct berval **out) { int rc = 0; /* success */ + ldbm_instance *inst = (ldbm_instance *)be->be_instance_info; + + if (!inst->attrcrypt_configured) { + /* No encryption is enabled in this backend at all. */ + return rc; + } if (ai->ai_attrcrypt) { Slapi_Value *value = NULL;
0
4a5e72af9e5b4b006ea5e997695bc959f79856f5
389ds/389-ds-base
Issue 5180 - snmp_collator tries to unlock NULL mutex (#5266) Bug description: A slapi_unlock_mutex is attempted on a NULL mutex. Fix description: SNMP collator is started if counters are enabled, but is stopped without checking if counters are enabled. A check is added before snmp_collator_stop() is called. Fixes: https://github.com/389ds/389-ds-base/issues/5180 Reviewed by: @mreynolds389 (Thank you)
commit 4a5e72af9e5b4b006ea5e997695bc959f79856f5 Author: James Chapman <[email protected]> Date: Thu Apr 14 15:55:56 2022 +0100 Issue 5180 - snmp_collator tries to unlock NULL mutex (#5266) Bug description: A slapi_unlock_mutex is attempted on a NULL mutex. Fix description: SNMP collator is started if counters are enabled, but is stopped without checking if counters are enabled. A check is added before snmp_collator_stop() is called. Fixes: https://github.com/389ds/389-ds-base/issues/5180 Reviewed by: @mreynolds389 (Thank you) diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index cdfcf76b2..d8dfea511 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -1248,12 +1248,14 @@ slapd_daemon(daemon_ports_t *ports) #endif if (!in_referral_mode) { - /* Close SNMP collator after the plugins closed... + /* Close SNMP collator (if counters are enabled) after the plugins closed... * Replication plugin still performs internal ops that * may try to increment snmp stats. * Fix for defect 523780 */ - snmp_collator_stop(); + if (config_get_slapi_counters()) { + snmp_collator_stop(); + } mapping_tree_free(); }
0
d5ba53748e69b3060be60889cd2081783ad6ff51
389ds/389-ds-base
Issue 5158: entryuuid fixup tasks fails in replicated topology (#5439) Problem: entryuuid plugin fixup task fails in replicated topology because o CSN is generated and the replication plugin aborts the operation. This happen because the operation flags are set to 0x400000 which is OP_FLAG_TOMBSTONE_FIXUP (a flags that should only be set to handle replication plugin internal operations) Solution: Do not use any flags
commit d5ba53748e69b3060be60889cd2081783ad6ff51 Author: progier389 <[email protected]> Date: Mon Sep 12 15:36:06 2022 +0200 Issue 5158: entryuuid fixup tasks fails in replicated topology (#5439) Problem: entryuuid plugin fixup task fails in replicated topology because o CSN is generated and the replication plugin aborts the operation. This happen because the operation flags are set to 0x400000 which is OP_FLAG_TOMBSTONE_FIXUP (a flags that should only be set to handle replication plugin internal operations) Solution: Do not use any flags diff --git a/dirsrvtests/tests/suites/entryuuid/replicated_test.py b/dirsrvtests/tests/suites/entryuuid/replicated_test.py index a2ebc8ff7..c956229d0 100644 --- a/dirsrvtests/tests/suites/entryuuid/replicated_test.py +++ b/dirsrvtests/tests/suites/entryuuid/replicated_test.py @@ -15,6 +15,8 @@ from lib389.paths import Paths from lib389.utils import ds_is_older from lib389._constants import * from lib389.replica import ReplicationManager +from lib389.plugins import EntryUUIDPlugin +from lib389.tasks import EntryUUIDFixupTask default_paths = Paths() @@ -75,3 +77,77 @@ def test_entryuuid_with_replication(topo_m2): assert(len(euuid_c) == 1) assert(euuid_c == euuid_a) [email protected](not default_paths.rust_enabled or ds_is_older('1.4.2.0'), reason="Entryuuid is not available in older versions") +def test_entryuuid_fixup_with_replication(topo_m2): + """ Check that entryuuid fixup task works with replication + + :id: 4ff25022-2de8-11ed-b393-482ae39447e5 + :setup: two node mmr + + :steps: + 1. Disable EntryUUID plugin. + 2. Create an user entry. + 3. Enable EntryUUID plugin. + 4. Check that the user entry does not have an entryuuid attribute + 5. Run fixup task + 6. Wait for task completion + 7. Check that the user entry has an entryuuid attribute + 8. Wait until changes get replicated + 9. Check that the user entry on the other supplier has same entryuuid attribute + + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + 5. Success + 6. Success + 7. Success + 8. Success + 9. Success + """ + server_a = topo_m2.ms["supplier1"] + server_b = topo_m2.ms["supplier2"] + server_a.config.loglevel(vals=(ErrorLog.DEFAULT,ErrorLog.TRACE)) + server_b.config.loglevel(vals=(ErrorLog.DEFAULT,ErrorLog.TRACE)) + + # 1. Disable EntryUUID plugin. + plugin = EntryUUIDPlugin(server_a) + plugin.disable() + server_a.restart() + + # 2. Create an user entry. + # uid must differ than the test test_entryuuid_with_replication one + # to avoid conflict between the tests. + account_a = nsUserAccounts(server_a, DEFAULT_SUFFIX).create_test_user(uid=3000) + + # 3. Enable EntryUUID plugin. + plugin.enable() + server_a.restart() + + # 4. Check that the user entry does not have an entryuuid attribute + euuid_a = account_a.get_attr_vals_utf8('entryUUID') + assert(not euuid_a) + + # 5. Run fixup task + task = EntryUUIDFixupTask(server_a).create(properties={ + 'basedn': DEFAULT_SUFFIX, + 'filter': "objectClass=*" + }) + + # 6. Wait for task completion + task.wait() + assert task.is_complete() + + # 7. Check that the user entry has an entryuuid attribute + euuid_a = account_a.get_attr_vals_utf8('entryUUID') + assert(euuid_a) + + # 8. Wait until changes get replicated + repl = ReplicationManager(DEFAULT_SUFFIX) + repl.wait_for_replication(server_b, server_a) + + # 9. Check that the user entry on the other supplier has same entryuuid attribute + account_b = nsUserAccounts(server_b, DEFAULT_SUFFIX).get("test_user_3000") + euuid_b = account_b.get_attr_vals_utf8('entryUUID') + assert euuid_a == euuid_b diff --git a/src/slapi_r_plugin/src/constants.rs b/src/slapi_r_plugin/src/constants.rs index 17282d719..1da9bcb70 100644 --- a/src/slapi_r_plugin/src/constants.rs +++ b/src/slapi_r_plugin/src/constants.rs @@ -5,11 +5,6 @@ use std::os::raw::c_char; pub const LDAP_SUCCESS: i32 = 0; pub const PLUGIN_DEFAULT_PRECEDENCE: i32 = 50; -#[repr(i32)] -pub enum OpFlags { - ByassReferrals = 0x0040_0000, -} - #[repr(i32)] /// The set of possible function handles we can register via the pblock. These /// values correspond to slapi-plugin.h. diff --git a/src/slapi_r_plugin/src/modify.rs b/src/slapi_r_plugin/src/modify.rs index b1a03a827..4d5c111c0 100644 --- a/src/slapi_r_plugin/src/modify.rs +++ b/src/slapi_r_plugin/src/modify.rs @@ -1,4 +1,3 @@ -use crate::constants::OpFlags; use crate::dn::SdnRef; use crate::error::{LDAPError, PluginError}; use crate::pblock::Pblock; @@ -95,7 +94,7 @@ impl Modify { std::ptr::null(), std::ptr::null(), plugin_id.raw_pid, - OpFlags::ByassReferrals as i32, + 0 as i32, ) };
0
17d86aef5a9a718857a03e9c8ada870fb65b84ce
389ds/389-ds-base
fix the url_parse logic when looking for a missing suffix DN The logic looking for a missing suffix DN in a parsed URL was incorrect. In addition, since passthru requires a suffix DN, pass the require_dn flag.
commit 17d86aef5a9a718857a03e9c8ada870fb65b84ce Author: Rich Megginson <[email protected]> Date: Thu Aug 12 17:51:10 2010 -0600 fix the url_parse logic when looking for a missing suffix DN The logic looking for a missing suffix DN in a parsed URL was incorrect. In addition, since passthru requires a suffix DN, pass the require_dn flag. diff --git a/ldap/servers/plugins/passthru/ptconfig.c b/ldap/servers/plugins/passthru/ptconfig.c index 92629d88b..850bd3d9a 100644 --- a/ldap/servers/plugins/passthru/ptconfig.c +++ b/ldap/servers/plugins/passthru/ptconfig.c @@ -238,7 +238,7 @@ passthru_config( int argc, char **argv ) /* * parse the LDAP URL */ - if (( rc = slapi_ldap_url_parse( srvr->ptsrvr_url, &ludp, 0, &secure )) != 0 ) { + if (( rc = slapi_ldap_url_parse( srvr->ptsrvr_url, &ludp, 1, &secure )) != 0 ) { slapi_log_error( SLAPI_LOG_FATAL, PASSTHRU_PLUGIN_SUBSYSTEM, "unable to parse LDAP URL \"%s\" (%s)\n", srvr->ptsrvr_url, slapi_urlparse_err2string( rc )); diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index 971628740..837f23ebd 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -155,13 +155,16 @@ slapi_ldap_url_parse(const char *url, LDAPURLDesc **ludpp, int require_dn, int * rc = ldap_url_parse_ext(url, ludpp, require_dn ? LDAP_PVT_URL_PARSE_NONE : LDAP_PVT_URL_PARSE_NOEMPTY_DN); #else rc = ldap_url_parse(url, ludpp); - if (rc || !*ludpp || !require_dn) { /* failed - see if failure was due to missing dn */ + if ((rc || !*ludpp) && !require_dn) { /* failed - see if failure was due to missing dn */ size_t len = strlen(url); /* assume the url is just scheme://host:port[/] - add the empty string as the DN (adding a trailing / first if needed) and try to parse again */ char *urlcopy = slapi_ch_smprintf("%s%s%s", url, (url[len-1] == '/' ? "" : "/"), ""); + if (*ludpp) { + ldap_free_urldesc(*ludpp); /* free the old one, if any */ + } rc = ldap_url_parse(urlcopy, ludpp); slapi_ch_free_string(&urlcopy); if (0 == rc) { /* only problem was the DN - free it */
0
56e4fac73a6fb04c6e440cdf1d5deac99ea04194
389ds/389-ds-base
Ticket #47424 - Replication problem with add-delete requests on single-valued attributes https://fedorahosted.org/389/ticket/47424 Reviewed by: lkrispenz (Thanks!) Branch: master Fix Description: Change the single master resolve attr code to handle the specific case of doing add: newvalue delete: oldvalue Had to add a new API function - csn_compare_ext - to be able to compare CSNs without the subsequence number. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no (cherry picked from commit 16e6fc20b51d94a22d73036f2809315b118bd5a4) (cherry picked from commit 90f170c7e697ba6350a9721b4a09b8a746e32431)
commit 56e4fac73a6fb04c6e440cdf1d5deac99ea04194 Author: Rich Megginson <[email protected]> Date: Wed Jul 17 17:51:36 2013 -0600 Ticket #47424 - Replication problem with add-delete requests on single-valued attributes https://fedorahosted.org/389/ticket/47424 Reviewed by: lkrispenz (Thanks!) Branch: master Fix Description: Change the single master resolve attr code to handle the specific case of doing add: newvalue delete: oldvalue Had to add a new API function - csn_compare_ext - to be able to compare CSNs without the subsequence number. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no (cherry picked from commit 16e6fc20b51d94a22d73036f2809315b118bd5a4) (cherry picked from commit 90f170c7e697ba6350a9721b4a09b8a746e32431) diff --git a/ldap/servers/slapd/csn.c b/ldap/servers/slapd/csn.c index 9fb5b4ac7..5c3168989 100644 --- a/ldap/servers/slapd/csn.c +++ b/ldap/servers/slapd/csn.c @@ -298,7 +298,7 @@ csn_as_attr_option_string(CSNType t,const CSN *csn,char *ss) } int -csn_compare(const CSN *csn1, const CSN *csn2) +csn_compare_ext(const CSN *csn1, const CSN *csn2, unsigned int flags) { PRInt32 retVal; if(csn1!=NULL && csn2!=NULL) @@ -321,7 +321,7 @@ csn_compare(const CSN *csn1, const CSN *csn2) retVal = -1; else if (csn1->rid > csn2->rid) retVal = 1; - else + else if (!(flags & CSN_COMPARE_SKIP_SUBSEQ)) { if (csn1->subseqnum < csn2->subseqnum) retVal = -1; @@ -330,6 +330,8 @@ csn_compare(const CSN *csn1, const CSN *csn2) else retVal = 0; } + else + retVal = 0; } } @@ -350,6 +352,12 @@ csn_compare(const CSN *csn1, const CSN *csn2) return(retVal); } +int +csn_compare(const CSN *csn1, const CSN *csn2) +{ + return csn_compare_ext(csn1, csn2, 0); +} + time_t csn_time_difference(const CSN *csn1, const CSN *csn2) { return csn_get_time(csn1) - csn_get_time(csn2); diff --git a/ldap/servers/slapd/entrywsi.c b/ldap/servers/slapd/entrywsi.c index 033535854..9040a1a47 100644 --- a/ldap/servers/slapd/entrywsi.c +++ b/ldap/servers/slapd/entrywsi.c @@ -757,7 +757,10 @@ entry_delete_present_values_wsi_single_valued(Slapi_Entry *e, const char *type, { valuearray_free(&deletedvalues); /* The attribute is single valued and the value was successful deleted */ - entry_present_attribute_to_deleted_attribute(e, a); + /* but there could have been an add in the same operation, so double check */ + if (valueset_isempty(&a->a_present_values)) { + entry_present_attribute_to_deleted_attribute(e, a); + } } else if (retVal != LDAP_SUCCESS) { @@ -875,8 +878,8 @@ entry_delete_present_values_wsi_multi_valued(Slapi_Entry *e, const char *type, s if ( retVal==LDAP_OPERATIONS_ERROR ) { LDAPDebug( LDAP_DEBUG_ANY, "Possible existing duplicate " - "value for attribute type %s found in " - "entry %s\n", a->a_type, slapi_entry_get_dn_const(e), 0 ); + "value for attribute type %s found in " + "entry %s\n", a->a_type, slapi_entry_get_dn_const(e), 0 ); } } valuearray_free(&valuestodelete); @@ -1327,6 +1330,7 @@ resolve_attribute_state_single_valued(Slapi_Entry *e, Slapi_Attr *a, int attribu Slapi_Value *new_value= NULL; const CSN *current_value_vucsn; const CSN *pending_value_vucsn; + const CSN *pending_value_vdcsn; const CSN *adcsn; int i; @@ -1340,27 +1344,47 @@ resolve_attribute_state_single_valued(Slapi_Entry *e, Slapi_Attr *a, int attribu slapi_attr_next_value(a,i,&new_value); } attr_first_deleted_value(a,&pending_value); - /* purge_attribute_state_single_valued */ adcsn= attr_get_deletion_csn(a); current_value_vucsn= value_get_csn(current_value, CSN_TYPE_VALUE_UPDATED); pending_value_vucsn= value_get_csn(pending_value, CSN_TYPE_VALUE_UPDATED); - if((pending_value!=NULL && (csn_compare(adcsn, pending_value_vucsn)<0)) || - (pending_value==NULL && (csn_compare(adcsn, current_value_vucsn)<0))) + pending_value_vdcsn= value_get_csn(pending_value, CSN_TYPE_VALUE_DELETED); + if((pending_value!=NULL && (csn_compare(adcsn, pending_value_vucsn)<0)) || + (pending_value==NULL && (csn_compare(adcsn, current_value_vucsn)<0))) { attr_set_deletion_csn(a,NULL); adcsn= NULL; - } + } - if(new_value==NULL) + /* in the case of the following: + * add: value2 + * delete: value1 + * we will have current_value with VUCSN CSN1 + * and pending_value with VDCSN CSN2 + * and new_value == NULL + * current_value != pending_value + * and + * VUCSN == VDCSN (ignoring subseq) + * even though value1.VDCSN > value2.VUCSN + * value2 should still win because the value is _different_ + */ + if (current_value && pending_value && !new_value && !adcsn && + (0 != slapi_value_compare(a, current_value, pending_value)) && + (0 == csn_compare_ext(current_value_vucsn, pending_value_vdcsn, CSN_COMPARE_SKIP_SUBSEQ))) { - /* check if the pending value should become the current value */ - if(pending_value!=NULL) + /* just remove the deleted value */ + entry_deleted_value_to_zapped_value(a,pending_value); + pending_value = NULL; + } + else if(new_value==NULL) + { + /* check if the pending value should become the current value */ + if(pending_value!=NULL) { if(!value_distinguished_at_csn(e,a,current_value,pending_value_vucsn)) { - /* attribute.current_value = attribute.pending_value; */ - /* attribute.pending_value = NULL; */ + /* attribute.current_value = attribute.pending_value; */ + /* attribute.pending_value = NULL; */ entry_present_value_to_zapped_value(a,current_value); entry_deleted_value_to_present_value(a,pending_value); current_value= pending_value; @@ -1369,12 +1393,12 @@ resolve_attribute_state_single_valued(Slapi_Entry *e, Slapi_Attr *a, int attribu pending_value_vucsn= NULL; } } - /* check if the current value should be deleted */ - if(current_value!=NULL) + /* check if the current value should be deleted */ + if(current_value!=NULL) { if(csn_compare(adcsn,current_value_vucsn)>0) /* check if the attribute was deleted after the value was last updated */ { - if(!value_distinguished_at_csn(e,a,current_value,current_value_vucsn)) + if(!value_distinguished_at_csn(e,a,current_value,current_value_vucsn)) { entry_present_value_to_zapped_value(a,current_value); current_value= NULL; @@ -1386,17 +1410,17 @@ resolve_attribute_state_single_valued(Slapi_Entry *e, Slapi_Attr *a, int attribu else /* addition of a new value */ { const CSN *new_value_vucsn= value_get_csn(new_value,CSN_TYPE_VALUE_UPDATED); - if(csn_compare(new_value_vucsn,current_value_vucsn)<0) + if(csn_compare(new_value_vucsn,current_value_vucsn)<0) { - /* - * if the new value was distinguished at the time the current value was added - * then the new value should become current - */ - if(value_distinguished_at_csn(e,a,new_value,current_value_vucsn)) + /* + * if the new value was distinguished at the time the current value was added + * then the new value should become current + */ + if(value_distinguished_at_csn(e,a,new_value,current_value_vucsn)) { - /* attribute.pending_value = attribute.current_value */ - /* attribute.current_value = new_value */ - if(pending_value==NULL) + /* attribute.pending_value = attribute.current_value */ + /* attribute.current_value = new_value */ + if(pending_value==NULL) { entry_present_value_to_deleted_value(a,current_value); } @@ -1412,62 +1436,62 @@ resolve_attribute_state_single_valued(Slapi_Entry *e, Slapi_Attr *a, int attribu } else { - /* new_value= NULL */ + /* new_value= NULL */ entry_present_value_to_zapped_value(a, new_value); new_value= NULL; } } - else /* new value is after the current value */ + else /* new value is after the current value */ { - if(!value_distinguished_at_csn(e, a, current_value, new_value_vucsn)) + if(!value_distinguished_at_csn(e, a, current_value, new_value_vucsn)) { - /* attribute.current_value = new_value */ + /* attribute.current_value = new_value */ entry_present_value_to_zapped_value(a, current_value); current_value= new_value; new_value= NULL; current_value_vucsn= new_value_vucsn; } - else /* value is distinguished - check if we should replace the current pending value */ + else /* value is distinguished - check if we should replace the current pending value */ { - if(csn_compare(new_value_vucsn, pending_value_vucsn)>0) + if(csn_compare(new_value_vucsn, pending_value_vucsn)>0) { - /* attribute.pending_value = new_value */ + /* attribute.pending_value = new_value */ entry_deleted_value_to_zapped_value(a,pending_value); entry_present_value_to_deleted_value(a,new_value); pending_value= new_value; new_value= NULL; pending_value_vucsn= new_value_vucsn; - } - } - } - } + } + } + } + } - /* - * This call ensures that the attribute does not have a pending_value + /* + * This call ensures that the attribute does not have a pending_value * or a deletion_csn that is earlier than the current_value. */ /* purge_attribute_state_single_valued */ - if((pending_value!=NULL && (csn_compare(adcsn, pending_value_vucsn)<0)) || - (pending_value==NULL && (csn_compare(adcsn, current_value_vucsn)<0))) + if((pending_value!=NULL && (csn_compare(adcsn, pending_value_vucsn)<0)) || + (pending_value==NULL && (csn_compare(adcsn, current_value_vucsn)<0))) { attr_set_deletion_csn(a,NULL); adcsn= NULL; - } + } - /* set attribute state */ - if(current_value==NULL) + /* set attribute state */ + if(current_value==NULL) { if(attribute_state==ATTRIBUTE_PRESENT) { entry_present_attribute_to_deleted_attribute(e, a); } } - else + else { if(attribute_state==ATTRIBUTE_DELETED) { entry_deleted_attribute_to_present_attribute(e, a); } - } + } } diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 027056b42..e964ae453 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -196,6 +196,8 @@ PRUint16 csn_get_seqnum(const CSN *csn); PRUint16 csn_get_subseqnum(const CSN *csn); char *csn_as_string(const CSN *csn, PRBool replicaIdOrder, char *ss); /* WARNING: ss must be CSN_STRSIZE bytes, or NULL. */ int csn_compare(const CSN *csn1, const CSN *csn2); +int csn_compare_ext(const CSN *csn1, const CSN *csn2, unsigned int flags); +#define CSN_COMPARE_SKIP_SUBSEQ 0x1 time_t csn_time_difference(const CSN *csn1, const CSN *csn2); size_t csn_string_size(); char *csn_as_attr_option_string(CSNType t,const CSN *csn,char *ss);
0
73ee04fa12cd1de3a5e47c109e79e31c1aaaa2ab
389ds/389-ds-base
Issue 4449 - dsconf replication monitor fails to retrieve database RUV - consumer (Unavailable) (#4451) Bug Description: "dsconf replication monitor" fails to retrieve database RUV entry from consumer and this appears into the Cockpit web UI too. The problem is that the bind credentials are not rightly propagated when trying to get the consumers agreement status. Then supplier credntials are used instead and RUV is searched anonymously because there is no bind dn in ldapi case. Fix Description: - Propagates the bind credentials when computing agreement status - Add a credential cache because now a replica password could get asked several times: when discovering the topology and when getting the agreement maxcsn - Testcase test_dsconf_replication_monitor is modified to: - Assert when getting "consumer (Unavalaible)" status - Add a step using a freshly generated Dirsrv instance (as dsconf does) rather than using the topology one FYI: although the feature was tested in test_dsconf_replication_monitor py.test the test does not hit the bug because of several side effects: - If consumer credentials are not provided the suplier credentials are used. - topology generated DirSrv instance has a bind DN. - topology masters have the same credentials DirSrv generated by dsconf (in ldapi case) have no bind DN and hits the bugs - Add a comment about nonlocal keyword Relates: #4449 Reviewers: firstyear droideck mreynolds Issue 4449: Add a comment about nonlocal keyword
commit 73ee04fa12cd1de3a5e47c109e79e31c1aaaa2ab Author: progier389 <[email protected]> Date: Tue Nov 24 19:22:49 2020 +0100 Issue 4449 - dsconf replication monitor fails to retrieve database RUV - consumer (Unavailable) (#4451) Bug Description: "dsconf replication monitor" fails to retrieve database RUV entry from consumer and this appears into the Cockpit web UI too. The problem is that the bind credentials are not rightly propagated when trying to get the consumers agreement status. Then supplier credntials are used instead and RUV is searched anonymously because there is no bind dn in ldapi case. Fix Description: - Propagates the bind credentials when computing agreement status - Add a credential cache because now a replica password could get asked several times: when discovering the topology and when getting the agreement maxcsn - Testcase test_dsconf_replication_monitor is modified to: - Assert when getting "consumer (Unavalaible)" status - Add a step using a freshly generated Dirsrv instance (as dsconf does) rather than using the topology one FYI: although the feature was tested in test_dsconf_replication_monitor py.test the test does not hit the bug because of several side effects: - If consumer credentials are not provided the suplier credentials are used. - topology generated DirSrv instance has a bind DN. - topology masters have the same credentials DirSrv generated by dsconf (in ldapi case) have no bind DN and hits the bugs - Add a comment about nonlocal keyword Relates: #4449 Reviewers: firstyear droideck mreynolds Issue 4449: Add a comment about nonlocal keyword diff --git a/dirsrvtests/tests/suites/clu/repl_monitor_test.py b/dirsrvtests/tests/suites/clu/repl_monitor_test.py index 11aa5b99b..b03d170c8 100644 --- a/dirsrvtests/tests/suites/clu/repl_monitor_test.py +++ b/dirsrvtests/tests/suites/clu/repl_monitor_test.py @@ -15,6 +15,8 @@ from lib389.tasks import * from lib389.utils import * from lib389.topologies import topology_m2 from lib389.cli_base import FakeArgs +from lib389.cli_base.dsrc import dsrc_arg_concat +from lib389.cli_base import connect_instance pytestmark = pytest.mark.tier0 @@ -40,7 +42,7 @@ def set_log_file(request): request.addfinalizer(fin) -def check_value_in_log_and_reset(content_list, second_list=None, single_value=None): +def check_value_in_log_and_reset(content_list, second_list=None, single_value=None, error_list=None): with open(LOG_FILE, 'r+') as f: file_content = f.read() @@ -57,6 +59,11 @@ def check_value_in_log_and_reset(content_list, second_list=None, single_value=No log.info('Check for "{}"'.format(single_value)) assert single_value in file_content + if error_list is not None: + log.info('Check that "{}" is not present'.format(error_list)) + for item in error_list: + assert item not in file_content + log.info('Reset log file') f.truncate(0) @@ -75,12 +82,14 @@ def test_dsconf_replication_monitor(topology_m2, set_log_file): 3. Run replication monitor with aliases option 4. Run replication monitor with --json option 5. Run replication monitor with .dsrc file created + 6. Run replication monitor with connections option as if using dsconf CLI :expectedresults: 1. Success 2. Success 3. Success 4. Success 5. Success + 6. Success """ m1 = topology_m2.ms["master1"] @@ -114,6 +123,9 @@ def test_dsconf_replication_monitor(topology_m2, set_log_file): 'Replica ID: 2', 'Status For Agreement: "001" (' + m1.host + ':' + str(m1.port)+')'] + error_list = ['consumer (Unavailable)', + 'Failed to retrieve database RUV entry from consumer'] + json_list = ['type', 'list', 'items', @@ -169,7 +181,7 @@ def test_dsconf_replication_monitor(topology_m2, set_log_file): log.info('Run replication monitor with connections option') get_repl_monitor_info(m1, DEFAULT_SUFFIX, log, args) - check_value_in_log_and_reset(content_list, connection_content) + check_value_in_log_and_reset(content_list, connection_content, error_list=error_list) log.info('Run replication monitor with aliases option') args.aliases = aliases @@ -192,6 +204,27 @@ def test_dsconf_replication_monitor(topology_m2, set_log_file): log.info('Run replication monitor when .dsrc file is present with content') get_repl_monitor_info(m1, DEFAULT_SUFFIX, log, args) check_value_in_log_and_reset(content_list, alias_content) + os.remove(os.path.expanduser(DSRC_HOME)) + + log.info('Run replication monitor with connections option as if using dsconf CLI') + # Perform same test than steps 2 test but without using directly the topology instance. + # but with an instance similar to those than dsconf cli generates: + # step 2 args + args.connections = connections + args.aliases = None + args.json = False + # args needed to generate an instance with dsrc_arg_concat + args.instance = 'master1' + args.basedn = None + args.binddn = None + args.bindpw = None + args.pwdfile = None + args.prompt = False + args.starttls = False + dsrc_inst = dsrc_arg_concat(args, None) + inst = connect_instance(dsrc_inst, True, args) + get_repl_monitor_info(inst, DEFAULT_SUFFIX, log, args) + check_value_in_log_and_reset(content_list, connection_content, error_list=error_list) if __name__ == '__main__': diff --git a/src/lib389/lib389/cli_conf/replication.py b/src/lib389/lib389/cli_conf/replication.py index 439665731..ce5d05617 100644 --- a/src/lib389/lib389/cli_conf/replication.py +++ b/src/lib389/lib389/cli_conf/replication.py @@ -369,9 +369,16 @@ def set_repl_config(inst, basedn, log, args): def get_repl_monitor_info(inst, basedn, log, args): connection_data = dsrc_to_repl_monitor(DSRC_HOME, log) + credentials_cache = {} # Additional details for the connections to the topology def get_credentials(host, port): + # credentials_cache is nonlocal to refer to the instance + # from enclosing function (get_repl_monitor_info)` + nonlocal credentials_cache + key = f'{host}:{port}' + if key in credentials_cache: + return credentials_cache[key] found = False if args.connections: connections = args.connections @@ -406,8 +413,10 @@ def get_repl_monitor_info(inst, basedn, log, args): binddn = input(f'\nEnter a bind DN for {host}:{port}: ').rstrip() bindpw = getpass(f"Enter a password for {binddn} on {host}:{port}: ").rstrip() - return {"binddn": binddn, - "bindpw": bindpw} + credentials = {"binddn": binddn, + "bindpw": bindpw} + credentials_cache[key] = credentials + return credentials repl_monitor = ReplicationMonitor(inst) report_dict = repl_monitor.generate_report(get_credentials, args.json) diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index 00401a636..cb9aac507 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -2561,9 +2561,10 @@ class ReplicationMonitor(object): else: self._log = logging.getLogger(__name__) - def _get_replica_status(self, instance, report_data, use_json): + def _get_replica_status(self, instance, report_data, use_json, get_credentials=None): """Load all of the status data to report and add new hostname:port pairs for future processing + :type get_credentials: function """ replicas_status = [] @@ -2577,6 +2578,13 @@ class ReplicationMonitor(object): for agmt in agmts.list(): host = agmt.get_attr_val_utf8_l("nsds5replicahost") port = agmt.get_attr_val_utf8_l("nsds5replicaport") + if get_credentials is not None: + credentials = get_credentials(host, port) + binddn = credentials["binddn"] + bindpw = credentials["bindpw"] + else: + binddn = instance.binddn + bindpw = instance.bindpw protocol = agmt.get_attr_val_utf8_l('nsds5replicatransportinfo') # Supply protocol here because we need it only for connection # and agreement status is already preformatted for the user output @@ -2584,9 +2592,9 @@ class ReplicationMonitor(object): if consumer not in report_data: report_data[f"{consumer}:{protocol}"] = None if use_json: - agmts_status.append(json.loads(agmt.status(use_json=True))) + agmts_status.append(json.loads(agmt.status(use_json=True, binddn=binddn, bindpw=bindpw))) else: - agmts_status.append(agmt.status()) + agmts_status.append(agmt.status(binddn=binddn, bindpw=bindpw)) replicas_status.append({"replica_id": replica_id, "replica_root": replica_root, "replica_status": "Available", @@ -2609,7 +2617,7 @@ class ReplicationMonitor(object): initial_inst_key = f"{self._instance.config.get_attr_val_utf8_l('nsslapd-localhost')}:{self._instance.config.get_attr_val_utf8_l('nsslapd-port')}" # Do this on an initial instance to get the agreements to other instances try: - report_data[initial_inst_key] = self._get_replica_status(self._instance, report_data, use_json) + report_data[initial_inst_key] = self._get_replica_status(self._instance, report_data, use_json, get_credentials) except ldap.LDAPError as e: self._log.debug(f"Connection to consumer ({supplier_hostname}:{supplier_port}) failed, error: {e}") report_data[initial_inst_key] = [{"replica_status": f"Unavailable - {e.args[0]['desc']}"}]
0
467146b9350421a4151ff09c949b5dced2c9872a
389ds/389-ds-base
Resolves: #484149 Summary: Clear directory manager password with password storage scheme other than clear crashes the server Description: 1) introducing a flag (_nss_initialized) and an API (slapd_nss_is_initialized) to represent NSS_Initialize is called or not. 2) in config_set_rootpw, if the directory manager's password is given unhashed, check if NSS is already initialized and the directory manager's password storage scheme is clear or not. If NSS is not initialized and if the storage scheme is not CLEAR, report it and return an error LDAP_PARAM_ERROR.
commit 467146b9350421a4151ff09c949b5dced2c9872a Author: Noriko Hosoi <[email protected]> Date: Thu Feb 5 17:34:56 2009 +0000 Resolves: #484149 Summary: Clear directory manager password with password storage scheme other than clear crashes the server Description: 1) introducing a flag (_nss_initialized) and an API (slapd_nss_is_initialized) to represent NSS_Initialize is called or not. 2) in config_set_rootpw, if the directory manager's password is given unhashed, check if NSS is already initialized and the directory manager's password storage scheme is clear or not. If NSS is not initialized and if the storage scheme is not CLEAR, report it and return an error LDAP_PARAM_ERROR. diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index bd2529c0a..ae476630e 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -2501,12 +2501,20 @@ config_set_rootpw( const char *attrname, char *value, char *errorbuf, int apply is_hashed = pw_val2scheme ( value, NULL, 0 ); if ( is_hashed ) { - slapdFrontendConfig->rootpw = slapi_ch_strdup ( value ); - free_pw_scheme(is_hashed); - } - else { - /* pwd enc func returns slapi_ch_malloc memory */ - slapdFrontendConfig->rootpw = (slapdFrontendConfig->rootpwstoragescheme->pws_enc)(value); + slapdFrontendConfig->rootpw = slapi_ch_strdup ( value ); + free_pw_scheme(is_hashed); + } else if (slapd_nss_is_initialized() || + (strcasecmp(slapdFrontendConfig->rootpwstoragescheme->pws_name, + "clear") == 0)) { + /* to hash, security library should have been initialized, by now */ + /* pwd enc func returns slapi_ch_malloc memory */ + slapdFrontendConfig->rootpw = (slapdFrontendConfig->rootpwstoragescheme->pws_enc)(value); + } else { + PR_snprintf ( errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, + "%s: password scheme mismatch (passwd scheme is %s; " + "password is clear text)", attrname, + slapdFrontendConfig->rootpwstoragescheme->pws_name); + retVal = LDAP_PARAM_ERROR; } CFG_UNLOCK_WRITE(slapdFrontendConfig); diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 8ff5caef8..115dcc2ae 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -1107,6 +1107,7 @@ time_t parse_genTime(char* from); /* Client SSL code */ int slapd_security_library_is_initialized( void ); +int slapd_nss_is_initialized( void ); char* slapd_get_tmp_dir( void ); /* util.c */ diff --git a/ldap/servers/slapd/ssl.c b/ldap/servers/slapd/ssl.c index c546c2bd8..0937e30ed 100644 --- a/ldap/servers/slapd/ssl.c +++ b/ldap/servers/slapd/ssl.c @@ -87,6 +87,7 @@ static char* dongle_file_name = NULL; static int _security_library_initialized = 0; static int _ssl_listener_initialized = 0; +static int _nss_initialized = 0; /* Our name for the internal token, must match PKCS-11 config data below */ static char *internalTokenName = "Internal (Software) Token"; @@ -469,6 +470,7 @@ slapd_nss_init(int init_ssl, int config_available) /****** end of NSS Initialization ******/ + _nss_initialized = 1; slapi_ch_free_string(&certdir); return rv; } @@ -1243,6 +1245,12 @@ slapd_ssl_listener_is_initialized() return _ssl_listener_initialized; } +int +slapd_nss_is_initialized() +{ + return _nss_initialized; +} + /* memory to store tmpdir is allocated and returned; caller should free it. */ char* slapd_get_tmp_dir() {
0
ecaebe9c8f8755b9493fcbe67621620b3870589a
389ds/389-ds-base
Ticket 48710 - auto-dn-suffix unrecognized option Bug Description: Configure would output the following error: configure: WARNING: unrecognized options: --enable-auto-dn-suffix However, the option was set correctly. Fix Description: The option was being registered with the name "autobind" so it was not correctly being check in autotools. https://fedorahosted.org/389/ticket/48710 Author: wibrown Contributors: Wes <[email protected]> (Thanks for finding the mistake!) Review by: nhosoi (Thanks!)
commit ecaebe9c8f8755b9493fcbe67621620b3870589a Author: William Brown <[email protected]> Date: Mon Apr 4 13:19:42 2016 +1000 Ticket 48710 - auto-dn-suffix unrecognized option Bug Description: Configure would output the following error: configure: WARNING: unrecognized options: --enable-auto-dn-suffix However, the option was set correctly. Fix Description: The option was being registered with the name "autobind" so it was not correctly being check in autotools. https://fedorahosted.org/389/ticket/48710 Author: wibrown Contributors: Wes <[email protected]> (Thanks for finding the mistake!) Review by: nhosoi (Thanks!) diff --git a/configure b/configure index 6a0324704..ecdc5eef6 100755 --- a/configure +++ b/configure @@ -921,6 +921,7 @@ enable_pam_passthru enable_dna enable_ldapi enable_autobind +enable_auto_dn_suffix enable_bitwise enable_presence enable_acctpolicy @@ -17907,9 +17908,9 @@ if test -z "$enable_auto_dn_suffix" ; then fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-auto-dn-suffix" >&5 $as_echo_n "checking for --enable-auto-dn-suffix... " >&6; } -# Check whether --enable-autobind was given. -if test "${enable_autobind+set}" = set; then : - enableval=$enable_autobind; +# Check whether --enable-auto-dn-suffix was given. +if test "${enable_auto_dn_suffix+set}" = set; then : + enableval=$enable_auto_dn_suffix; fi if test "$enable_ldapi" = yes -a "$enable_autobind" = yes -a "$enable_auto_dn_suffix" = "yes"; then diff --git a/configure.ac b/configure.ac index c520022d4..4be46135f 100644 --- a/configure.ac +++ b/configure.ac @@ -185,7 +185,7 @@ if test -z "$enable_auto_dn_suffix" ; then enable_auto_dn_suffix=no # if not set on cmdline, set default fi AC_MSG_CHECKING(for --enable-auto-dn-suffix) -AC_ARG_ENABLE(autobind, +AC_ARG_ENABLE(auto-dn-suffix, AS_HELP_STRING([--enable-auto-dn-suffix], [enable auto bind with auto dn suffix over unix domain socket (LDAPI) support (default: no)])) if test "$enable_ldapi" = yes -a "$enable_autobind" = yes -a "$enable_auto_dn_suffix" = "yes"; then
0
3e1d97624f390b96c1de21b115619822b72ebf98
389ds/389-ds-base
Ticket 47451 - Fix jenkins errors Description: Fix compiler warnings https://fedorahosted.org/389/ticket/47451
commit 3e1d97624f390b96c1de21b115619822b72ebf98 Author: Mark Reynolds <[email protected]> Date: Tue Dec 16 16:10:05 2014 -0500 Ticket 47451 - Fix jenkins errors Description: Fix compiler warnings https://fedorahosted.org/389/ticket/47451 diff --git a/ldap/servers/plugins/dna/dna.c b/ldap/servers/plugins/dna/dna.c index ded0bbb45..f4a36f015 100644 --- a/ldap/servers/plugins/dna/dna.c +++ b/ldap/servers/plugins/dna/dna.c @@ -2406,7 +2406,7 @@ static int dna_get_next_value(struct configEntry *config_entry, } else { /* dna_first_free_value() failed for some unknown reason */ slapi_log_error(SLAPI_LOG_FATAL, DNA_PLUGIN_SUBSYSTEM, - "dna_get_next_value: failed to allocate a new ID!! (set(%d) (max: %d)\n",setval,config_entry->maxval); + "dna_get_next_value: failed to allocate a new ID!!\n"); goto done; } } @@ -3415,8 +3415,6 @@ _dna_pre_op_add(Slapi_PBlock *pb, Slapi_Entry *e, char **errstr) /* dna_first_free_value() failed for some unknown reason */ slapi_log_error(SLAPI_LOG_FATAL, DNA_PLUGIN_SUBSYSTEM, "dna_pre_op: failed to allocate a new ID!! 2\n"); - slapi_log_error(SLAPI_LOG_FATAL, DNA_PLUGIN_SUBSYSTEM, - "dna_get_next_value: failed to allocate a new ID!! (set(%d) (max: %d)\n",setval,config_entry->maxval); /* Set an error string to be returned to the client. */ *errstr = slapi_ch_smprintf("Allocation of a new value for range" " %s failed! Unable to proceed.", @@ -3682,8 +3680,6 @@ _dna_pre_op_modify(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Mods *smods, char **e /* dna_first_free_value() failed for some unknown reason */ slapi_log_error(SLAPI_LOG_FATAL, DNA_PLUGIN_SUBSYSTEM, "dna_pre_op: failed to allocate a new ID!!\n"); - slapi_log_error(SLAPI_LOG_FATAL, DNA_PLUGIN_SUBSYSTEM, - "dna_get_next_value: failed to allocate a new ID!! (set(%d) (max: %d)\n",setval,config_entry->maxval); /* Set an error string to be returned to the client. */ *errstr = slapi_ch_smprintf("Allocation of a new value for range" " %s failed! Unable to proceed.", diff --git a/ldap/servers/plugins/uiduniq/uid.c b/ldap/servers/plugins/uiduniq/uid.c index f37ab8cb0..2120b4f40 100644 --- a/ldap/servers/plugins/uiduniq/uid.c +++ b/ldap/servers/plugins/uiduniq/uid.c @@ -1285,7 +1285,6 @@ uiduniq_start(Slapi_PBlock *pb) static int uiduniq_close(Slapi_PBlock *pb) { - Slapi_Entry *plugin_entry = NULL; struct attr_uniqueness_config *config = NULL; slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &config); @@ -1312,7 +1311,6 @@ NSUniqueAttr_Init(Slapi_PBlock *pb) int preadd = SLAPI_PLUGIN_PRE_ADD_FN; int premod = SLAPI_PLUGIN_PRE_MODIFY_FN; int premdn = SLAPI_PLUGIN_PRE_MODRDN_FN; - struct attr_uniqueness_config *config = NULL; BEGIN
0
b67f0f822911d0abd4467734a7150c6a94635b82
389ds/389-ds-base
Ticket 49599 - Revise replication total init status messages Description: Previously the replication update status messages were updated to a more readable format. This should also be done with the total update status messages. https://pagure.io/389-ds-base/issue/49599 Reviewed by: lkrispen(Thanks!)
commit b67f0f822911d0abd4467734a7150c6a94635b82 Author: Mark Reynolds <[email protected]> Date: Mon Mar 12 09:36:29 2018 -0400 Ticket 49599 - Revise replication total init status messages Description: Previously the replication update status messages were updated to a more readable format. This should also be done with the total update status messages. https://pagure.io/389-ds-base/issue/49599 Reviewed by: lkrispen(Thanks!) diff --git a/ldap/servers/plugins/replication/repl5_agmt.c b/ldap/servers/plugins/replication/repl5_agmt.c index ee396c8ef..d71d3f38b 100644 --- a/ldap/servers/plugins/replication/repl5_agmt.c +++ b/ldap/servers/plugins/replication/repl5_agmt.c @@ -2523,7 +2523,7 @@ agmt_set_last_init_status(Repl_Agmt *ra, int ldaprc, int replrc, int connrc, con replmsg = NULL; } } - PR_snprintf(ra->last_init_status, STATUS_LEN, "%d %s%sLDAP error: %s%s%s%s%s", + PR_snprintf(ra->last_init_status, STATUS_LEN, "Error (%d) %s%sLDAP error: %s%s%s%s%s", ldaprc, message ? message : "", message ? "" : " - ", slapi_err2string(ldaprc), replmsg ? " - " : "", replmsg ? replmsg : "", connrc ? " - " : "", connrc ? connmsg : ""); @@ -2531,7 +2531,7 @@ agmt_set_last_init_status(Repl_Agmt *ra, int ldaprc, int replrc, int connrc, con /* ldaprc == LDAP_SUCCESS */ else if (replrc != 0) { if (replrc == NSDS50_REPL_REPLICA_RELEASE_SUCCEEDED) { - PR_snprintf(ra->last_init_status, STATUS_LEN, "%d %s", + PR_snprintf(ra->last_init_status, STATUS_LEN, "Error (%d) %s", ldaprc, "Replication session successful"); } else if (replrc == NSDS50_REPL_DISABLED) { if (agmt_is_enabled(ra)) { @@ -2539,7 +2539,7 @@ agmt_set_last_init_status(Repl_Agmt *ra, int ldaprc, int replrc, int connrc, con "Replication agreement for \"%s\" can not be updated while the suffix is disabled.\n" "You must enable it then restart the server for replication to take place).\n", ra->long_name ? ra->long_name : "a replica"); - PR_snprintf(ra->last_init_status, STATUS_LEN, "%d Total update aborted: " + PR_snprintf(ra->last_init_status, STATUS_LEN, "Error (%d) Total update aborted: " "Replication agreement for \"%s\" can not be updated while the suffix is disabled.\n" "You must enable it then restart the server for replication to take place).", replrc, ra->long_name ? ra->long_name : "a replica"); @@ -2548,29 +2548,29 @@ agmt_set_last_init_status(Repl_Agmt *ra, int ldaprc, int replrc, int connrc, con slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "Total update aborted: " "Replication agreement for \"%s\" can not be updated while the agreement is disabled\n", ra->long_name ? ra->long_name : "a replica"); - PR_snprintf(ra->last_init_status, STATUS_LEN, "%d Total update aborted: " + PR_snprintf(ra->last_init_status, STATUS_LEN, "Error (%d) Total update aborted: " "Replication agreement for \"%s\" can not be updated while the agreement is disabled.", replrc, ra->long_name ? ra->long_name : "a replica"); } } else { PR_snprintf(ra->last_init_status, STATUS_LEN, - "%d Replication error acquiring replica: %s%s%s%s%s", + "Error (%d) Replication error acquiring replica: %s%s%s%s%s", replrc, protocol_response2string(replrc), message ? " - " : "", message ? message : "", connrc ? " - " : "", connrc ? connmsg : ""); } } else if (connrc != CONN_OPERATION_SUCCESS) { PR_snprintf(ra->last_init_status, STATUS_LEN, - "%d connection error: %s%s%s", + "Error (%d) connection error: %s%s%s", connrc, connmsg, message ? " - " : "", message ? message : ""); } else if (message != NULL) /* replrc == NSDS50_REPL_REPLICA_READY == 0 */ { PR_snprintf(ra->last_init_status, STATUS_LEN, - "%d %s", + "Error (%d) %s", ldaprc, message); } else { /* agmt_set_last_init_status(0,0,NULL) to reset agmt */ - PR_snprintf(ra->last_init_status, STATUS_LEN, "%d", ldaprc); + PR_snprintf(ra->last_init_status, STATUS_LEN, "Error (%d)", ldaprc); } } }
0
6343d861e6615cf6e99b06f82d50811f20e8884d
389ds/389-ds-base
516089 RFE: ldclt utility should support new dereferencing control searches Adding "-e deref" option to ldclt. Add mode (-e add): "-e deref" adds "secretary: <DN>" to the entry. This is true when the entry's objectclass is inetOrgPerson (-e inetOrgPerson"). Search mode (-e esearch): "-e deref" sets dereference control to the search, where the dereference attribute and dereferenced attribute are hardcoded to "secretary" and "cn", respectively. Usage: ldclt [...] -e add -e random -e inetOrgPerson -e deref -f test_XX ldclt [...] -e esearch -e random -e inetOrgPerson -e deref -f test_XX
commit 6343d861e6615cf6e99b06f82d50811f20e8884d Author: Noriko Hosoi <[email protected]> Date: Tue Sep 1 13:44:14 2009 -0700 516089 RFE: ldclt utility should support new dereferencing control searches Adding "-e deref" option to ldclt. Add mode (-e add): "-e deref" adds "secretary: <DN>" to the entry. This is true when the entry's objectclass is inetOrgPerson (-e inetOrgPerson"). Search mode (-e esearch): "-e deref" sets dereference control to the search, where the dereference attribute and dereferenced attribute are hardcoded to "secretary" and "cn", respectively. Usage: ldclt [...] -e add -e random -e inetOrgPerson -e deref -f test_XX ldclt [...] -e esearch -e random -e inetOrgPerson -e deref -f test_XX diff --git a/ldap/servers/slapd/tools/ldclt/ldapfct.c b/ldap/servers/slapd/tools/ldclt/ldapfct.c index a2382b7f9..74b1812bf 100644 --- a/ldap/servers/slapd/tools/ldclt/ldapfct.c +++ b/ldap/servers/slapd/tools/ldclt/ldapfct.c @@ -262,9 +262,8 @@ dd/mm/yy | Author | Comments #include <prprf.h> - - - +#define LDCLT_DEREF_ATTR "secretary" +int ldclt_create_deref_control( LDAP *ld, char *derefAttr, char **attrs, LDAPControl **ctrlp ); /* **************************************************************************** FUNCTION : my_ldap_err2string @@ -1725,6 +1724,15 @@ buildNewEntry ( if (addAttrib (attrs, nbAttribs++, &attribute) < 0) return (-1); } + if ((mctx.mode & OC_INETORGPRSON) && (mctx.mod2 & M2_DEREF)) + { + attribute.mod_op = LDAP_MOD_ADD; + attribute.mod_type = LDCLT_DEREF_ATTR; + /* refer itself */ + attribute.mod_values = strList1 (newDn); + if (addAttrib (attrs, nbAttribs++, &attribute) < 0) + return (-1); + } } /* @@ -3439,6 +3447,7 @@ doExactSearch ( int ret; /* Return value */ LDAPMessage *res; /* LDAP results */ char **attrlist; /* Attribs list */ /*JLS 15-03-01*/ + LDAPControl **ctrlsp = NULL, *ctrls[2], *dctrl = NULL; /* derefence control */ /* * Connection to the server @@ -3469,6 +3478,32 @@ doExactSearch ( else /*JLS 15-03-01*/ attrlist = mctx.attrlist; /*JLS 15-03-01*/ + if (mctx.mod2 & M2_DEREF) /* dereference */ + { + char *attrs[2]; + attrs[0] = "cn"; + attrs[1] = NULL; + ret = ldclt_create_deref_control(tttctx->ldapCtx, + LDCLT_DEREF_ATTR, attrs, &dctrl); + if (LDAP_SUCCESS == ret) + { + ctrls[0] = dctrl; + ctrls[1] = NULL; + ctrlsp = ctrls; + } + else + { + if (!((mctx.mode & QUIET) && ignoreError (ret))) + fprintf (stderr, + "ldclt[%d]: T%03d: ldclt_create_deref_control() failed, error=%d\n", + mctx.pid, tttctx->thrdNum, ret); + if (dctrl) { + ldap_control_free(dctrl); + } + if (addErrorStat(ret) < 0) + return (-1); + } + } /* * Do the search * Maybe we are in synchronous mode ? I hope so, it is really @@ -3478,45 +3513,57 @@ doExactSearch ( { ret = ldap_search_ext_s (tttctx->ldapCtx, tttctx->bufBaseDN, mctx.scope, tttctx->bufFilter, attrlist, /*JLS 15-03-01*/ - mctx.attrsonly, NULL, NULL, NULL, -1, &res); /*JLS 03-01-01*/ + mctx.attrsonly, ctrlsp, NULL, NULL, -1, &res); /*JLS 03-01-01*/ if (ret != LDAP_SUCCESS) { if (!((mctx.mode & QUIET) && ignoreError (ret))) (void) printErrorFromLdap (tttctx, res, ret, /*JLS 03-08-00*/ "Cannot ldap_search()"); /*JLS 03-08-00*/ if (addErrorStat (ret) < 0) - return (-1); + { + goto bail; + } if ((ret == LDAP_NO_SUCH_OBJECT) && /*JLS 15-12-00*/ (mctx.mode & COUNT_EACH)) /*JLS 15-12-00*/ { /*JLS 15-12-00*/ - if (incrementNbOpers (tttctx) < 0) /*JLS 15-12-00*/ - return (-1); /*JLS 15-12-00*/ + if (incrementNbOpers (tttctx) < 0) /*JLS 15-12-00*/ + { + goto bail; + } } /*JLS 15-12-00*/ } else { if (incrementNbOpers (tttctx) < 0)/* Memorize operation */ - return (-1); + { + goto bail; + } /* * Don't forget to free the returned message ! */ if ((ret = ldap_msgfree (res)) < 0) { - if (!((mctx.mode & QUIET) && ignoreError (ret))) - { - printf ("ldclt[%d]: T%03d: Cannot ldap_msgfree(), error=%d (%s)\n", - mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); - fflush (stdout); - } - if (addErrorStat (ret) < 0) - return (-1); + if (!((mctx.mode & QUIET) && ignoreError (ret))) + { + printf ("ldclt[%d]: T%03d: Cannot ldap_msgfree(), error=%d (%s)\n", + mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); + fflush (stdout); + } + if (addErrorStat (ret) < 0) + { + goto bail; + } } } /* * End of synchronous operation */ + if (dctrl) + { + ldap_control_free(dctrl); + } return (0); } @@ -3537,7 +3584,9 @@ doExactSearch ( (void) printErrorFromLdap (tttctx, res, ret, /*JLS 03-08-00*/ "Cannot ldap_result()"); /*JLS 03-08-00*/ if (addErrorStat (ret) < 0) - return (-1); + { + goto bail; + } } else { @@ -3548,14 +3597,16 @@ doExactSearch ( */ if ((ret = ldap_msgfree (res)) < 0) { - if (!((mctx.mode & QUIET) && ignoreError (ret))) - { - printf ("ldclt[%d]: T%03d: Cannot ldap_msgfree(), error=%d (%s)\n", - mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); - fflush (stdout); - } - if (addErrorStat (ret) < 0) - return (-1); + if (!((mctx.mode & QUIET) && ignoreError (ret))) + { + printf ("ldclt[%d]: T%03d: Cannot ldap_msgfree(), error=%d (%s)\n", + mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); + fflush (stdout); + } + if (addErrorStat (ret) < 0) + { + goto bail; + } } } } @@ -3594,32 +3645,33 @@ doExactSearch ( ret = ldap_search_ext (tttctx->ldapCtx, tttctx->bufBaseDN, mctx.scope, tttctx->bufFilter, attrlist, /*JLS 15-03-01*/ - mctx.attrsonly, NULL, NULL, NULL, -1, &msgid); /*JLS 03-01-01*/ + mctx.attrsonly, ctrlsp, NULL, NULL, -1, &msgid); /*JLS 03-01-01*/ if (ret < 0) { if (ldap_get_option (tttctx->ldapCtx, LDAP_OPT_ERROR_NUMBER, &ret) < 0) { - printf ("ldclt[%d]: T%03d: Cannot ldap_get_option(LDAP_OPT_ERROR_NUMBER)\n", - mctx.pid, tttctx->thrdNum); - fflush (stdout); - return (-1); + printf ("ldclt[%d]: T%03d: Cannot ldap_get_option(LDAP_OPT_ERROR_NUMBER)\n", + mctx.pid, tttctx->thrdNum); + fflush (stdout); + goto bail; } else { - if (!((mctx.mode & QUIET) && ignoreError (ret))) - { - printf ("ldclt[%d]: T%03d: Cannot ldap_search(), error=%d (%s)\n", - mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); - fflush (stdout); - } - if (addErrorStat (ret) < 0) - return (-1); - if ((ret == LDAP_NO_SUCH_OBJECT) && /*JLS 15-12-00*/ - (mctx.mode & COUNT_EACH)) /*JLS 15-12-00*/ - { /*JLS 15-12-00*/ - if (incrementNbOpers (tttctx) < 0) /*JLS 15-12-00*/ - return (-1); /*JLS 15-12-00*/ - } /*JLS 15-12-00*/ + if (!((mctx.mode & QUIET) && ignoreError (ret))) + { + printf ("ldclt[%d]: T%03d: Cannot ldap_search(), error=%d (%s)\n", + mctx.pid, tttctx->thrdNum, ret, my_ldap_err2string (ret)); + fflush (stdout); + } + if (addErrorStat (ret) < 0) + return (-1); + if ((ret == LDAP_NO_SUCH_OBJECT) && /*JLS 15-12-00*/ + (mctx.mode & COUNT_EACH)) /*JLS 15-12-00*/ + { /*JLS 15-12-00*/ + if (incrementNbOpers (tttctx) < 0) { /*JLS 15-12-00*/ + goto bail; + } + } /*JLS 15-12-00*/ } } else @@ -3627,8 +3679,9 @@ doExactSearch ( /* * Memorize the operation */ - if (incrementNbOpers (tttctx) < 0) - return (-1); + if (incrementNbOpers (tttctx) < 0) { + goto bail; + } tttctx->pendingNb++; } } @@ -3640,7 +3693,18 @@ doExactSearch ( /* * End of asynchronous operation... and also end of function. */ + if (dctrl) + { + ldap_control_free(dctrl); + } return (0); + +bail: + if (dctrl) + { + ldap_control_free(dctrl); + } + return (-1); } /* **************************************************************************** @@ -3813,4 +3877,42 @@ doAbandon (thread_context *tttctx) return (0); } +#define LDAP_CONTROL_X_DEREF "1.3.6.1.4.1.4203.666.5.16" +int +ldclt_create_deref_control( + LDAP *ld, + char *derefAttr, + char **attrs, + LDAPControl **ctrlp +) +{ + BerElement *ber; + int rc; + + if (ld == 0) { + return( LDAP_PARAM_ERROR ); + } + + if ( NULL == ctrlp || NULL == derefAttr || + NULL == attrs || NULL == *attrs || 0 == strlen(*attrs) ) { + return ( LDAP_PARAM_ERROR ); + } + + /* create a ber package to hold the controlValue */ + if ( LDAP_SUCCESS != nsldapi_alloc_ber_with_options( ld, &ber ) ) + { + return( LDAP_NO_MEMORY ); + } + + if ( LBER_ERROR == ber_printf( ber, "{{s{v}}}", derefAttr, attrs )) + { + ber_free( ber, 1 ); + return( LDAP_ENCODING_ERROR ); + } + + rc = nsldapi_build_control( LDAP_CONTROL_X_DEREF, ber, 1, 1, ctrlp ); + + return( rc ); +} + /* End of file */ diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.c b/ldap/servers/slapd/tools/ldclt/ldclt.c index f98233ccd..753b2148a 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.c +++ b/ldap/servers/slapd/tools/ldclt/ldclt.c @@ -2121,6 +2121,8 @@ char *execParams[] = { "randomauthidlow", #define EP_ABANDON 49 "abandon", +#define EP_DEREF 50 + "deref", NULL }; @@ -2406,6 +2408,9 @@ decodeExecParams ( case EP_ABANDON: mctx.mod2 |= M2_ABANDON; break; + case EP_DEREF: + mctx.mod2 |= M2_DEREF; + break; default: fprintf (stderr, "Error: illegal option -e %s\n", subvalue); return (-1); diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.h b/ldap/servers/slapd/tools/ldclt/ldclt.h index 8fa03d8b0..ee774f58e 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.h +++ b/ldap/servers/slapd/tools/ldclt/ldclt.h @@ -278,6 +278,7 @@ dd/mm/yy | Author | Comments #define M2_SASLAUTH 0x00000040 /* -o : SASL authentication */ #define M2_RANDOM_SASLAUTHID 0x00000080 /* -e randomauthid */ #define M2_ABANDON 0x00000100 /* -e abandon */ +#define M2_DEREF 0x00000200 /* -e deref */ /* * Combinatory defines diff --git a/ldap/servers/slapd/tools/ldclt/ldcltU.c b/ldap/servers/slapd/tools/ldclt/ldcltU.c index aa5fb705d..b002310f7 100644 --- a/ldap/servers/slapd/tools/ldclt/ldcltU.c +++ b/ldap/servers/slapd/tools/ldclt/ldcltU.c @@ -79,6 +79,8 @@ * commoncounter : all threads share the same counter. * counteach : count each operation not only successful ones. * delete : ldap_delete() entries. + * deref : adds dereference control to "esearch" + * : adds "secretary" attr to the entries for "add" * dontsleeponserverdown : will loop very fast if server down. * emailPerson : objectclass=emailPerson (-e add only). * esearch : exact search. @@ -171,6 +173,8 @@ void usage () (void) printf (" commoncounter : all threads share the same counter.\n"); (void) printf (" counteach : count each operation not only successful ones.\n"); (void) printf (" delete : ldap_delete() entries.\n"); + (void) printf (" deref : adds dereference control to \"esearch\"\n"); + (void) printf (" : adds \"secretary\" attr to the entries for \"add\"\n"); (void) printf (" dontsleeponserverdown : will loop very fast if server down.\n"); (void) printf (" emailPerson : objectclass=emailPerson (-e add only).\n"); (void) printf (" esearch : exact search.\n");
0
c013442930d30e81bb30fea22fe007b6645ecf62
389ds/389-ds-base
Trac Ticket #34 - remove-ds.pl does not remove everything https://fedorahosted.org/389/ticket/34 Fix description: Introduce an option "--all | -a", with which all the generated files and directories are removed.
commit c013442930d30e81bb30fea22fe007b6645ecf62 Author: Noriko Hosoi <[email protected]> Date: Mon Feb 13 15:45:45 2012 -0800 Trac Ticket #34 - remove-ds.pl does not remove everything https://fedorahosted.org/389/ticket/34 Fix description: Introduce an option "--all | -a", with which all the generated files and directories are removed. diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index 00d290c7e..7bb4595f2 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -1224,6 +1224,7 @@ sub stopServer { sub removeDSInstance { my $inst = shift; my $force = shift; + my $all = shift; my $initconfig_dir = shift || get_initconfigdir(); my $baseconfigdir = $ENV{DS_CONFIG_DIR} || "@instconfigdir@"; my $instname = "slapd-$inst"; @@ -1314,8 +1315,8 @@ sub removeDSInstance { push @errs, remove_tree($dbentry, "nsslapd-db-logdirectory", $instname, 1); } if ($entry) { - push @errs, remove_tree($entry, "nsslapd-lockdir", $instname); - push @errs, remove_tree($entry, "nsslapd-tmpdir", $instname); + push @errs, remove_tree($entry, "nsslapd-lockdir", $instname, 0); + push @errs, remove_tree($entry, "nsslapd-tmpdir", $instname, 0); push @errs, remove_tree($entry, "nsslapd-bakdir", $instname, 1); push @errs, remove_tree($entry, "nsslapd-errorlog", $instname, 1); } @@ -1335,7 +1336,11 @@ sub removeDSInstance { } } # Finally, config dir - push @errs, remove_tree($entry, "nsslapd-schemadir", $instname, 1, "\.db\$"); + if ($all) { + push @errs, remove_tree($entry, "nsslapd-schemadir", $instname, 1); + } else { + push @errs, remove_tree($entry, "nsslapd-schemadir", $instname, 1, "\.db\$"); + } # Remove the instance specific initconfig script if ( -f $initconfig ) { diff --git a/ldap/admin/src/scripts/remove-ds.pl.in b/ldap/admin/src/scripts/remove-ds.pl.in index 5eee37da2..5f4261507 100755 --- a/ldap/admin/src/scripts/remove-ds.pl.in +++ b/ldap/admin/src/scripts/remove-ds.pl.in @@ -43,12 +43,14 @@ sub usage { my $force = ""; my $instname = ""; my $initconfig_dir = ""; +my $all = ""; GetOptions('help|h|?' => sub { &usage; exit(1); }, 'debug|d+' => \$DSUtil::debuglevel, 'instance|i=s' => \$instname, 'initconfig_dir|c=s' => \$initconfig_dir, - 'force|f' => \$force + 'force|f' => \$force, + 'all|a' => \$all ); # Make sure the instance name option was provided. @@ -63,7 +65,7 @@ unless ($inst) { exit 1; } -my @errs = removeDSInstance($inst, $force, $initconfig_dir); +my @errs = removeDSInstance($inst, $force, $all, $initconfig_dir); if (@errs) { print STDERR "The following errors occurred during removal:\n"; for (@errs) {
0
654c62253e13df368be9a2e1b89e03771e363041
389ds/389-ds-base
Skip syntax check of encrypted attributes during import. When importing an ldif with pre-encrypted attributes, we need to skip the syntax check to avoid the import of those entries being skipped. The fix makes a copy of an entry with encrypted attributes, removes the encrypted attribtues, and uses this trimmed copy for the syntax check.
commit 654c62253e13df368be9a2e1b89e03771e363041 Author: Nathan Kinder <[email protected]> Date: Mon Jul 20 09:30:15 2009 -0700 Skip syntax check of encrypted attributes during import. When importing an ldif with pre-encrypted attributes, we need to skip the syntax check to avoid the import of those entries being skipped. The fix makes a copy of an entry with encrypted attributes, removes the encrypted attribtues, and uses this trimmed copy for the syntax check. diff --git a/ldap/servers/slapd/back-ldbm/import-threads.c b/ldap/servers/slapd/back-ldbm/import-threads.c index e0f00750c..b5e4e07fd 100644 --- a/ldap/servers/slapd/back-ldbm/import-threads.c +++ b/ldap/servers/slapd/back-ldbm/import-threads.c @@ -359,6 +359,7 @@ void import_producer(void *param) Slapi_Entry *e = NULL; struct backentry *ep = NULL, *old_ep = NULL; ldbm_instance *inst = job->inst; + backend *be = inst->inst_be; PRIntervalTime sleeptime; char *estr = NULL; int str2entry_flags = @@ -406,6 +407,7 @@ void import_producer(void *param) int flags = 0; int prev_lineno = 0; int lines_in_entry = 0; + int syntax_err = 0; if (job->flags & FLAG_ABORT) { goto error; @@ -546,8 +548,49 @@ void import_producer(void *param) continue; } + /* If we are importing pre-encrypted attributes, we need + * to skip syntax checks for the encrypted values. */ + if (!(job->encrypt) && inst->attrcrypt_configured) { + Slapi_Attr *attr = NULL; + Slapi_Entry *e_copy = NULL; + + /* Scan through the entry to see if any present + * attributes are configured for encryption. */ + slapi_entry_first_attr(e, &attr); + while (attr) { + char *type = NULL; + struct attrinfo *ai = NULL; + + slapi_attr_get_type(attr, &type); + + /* Check if this type is configured for encryption. */ + ainfo_get(be, type, &ai); + if (ai->ai_attrcrypt != NULL) { + /* Make a copy of the entry to use for syntax + * checking if a copy has not been made yet. */ + if (e_copy == NULL) { + e_copy = slapi_entry_dup(e); + } + + /* Delete the enrypted attribute from the copy. */ + slapi_entry_attr_delete(e_copy, type); + } + + slapi_entry_next_attr(e, attr, &attr); + } + + if (e_copy) { + syntax_err = slapi_entry_syntax_check(NULL, e_copy, 0); + slapi_entry_free(e_copy); + } else { + syntax_err = slapi_entry_syntax_check(NULL, e, 0); + } + } else { + syntax_err = slapi_entry_syntax_check(NULL, e, 0); + } + /* Check attribute syntax */ - if (slapi_entry_syntax_check(NULL, e, 0) != 0) + if (syntax_err != 0) { char ebuf[BUFSIZ]; import_log_notice(job, "WARNING: skipping entry \"%s\" which "
0
4d564ef42db022a5102c9b6ae1bdd41a18c1dd7f
389ds/389-ds-base
Update the slapi-plugin documentation on new slapi functions, and added a slapi function for checking on shutdowns Fix Description: removed the g_get_shutdown() functions from the plugins, and replaced them with the slapi version Reviewed by: Richm (Thanks!)
commit 4d564ef42db022a5102c9b6ae1bdd41a18c1dd7f Author: Mark Reynolds <[email protected]> Date: Wed May 30 13:30:44 2012 -0400 Update the slapi-plugin documentation on new slapi functions, and added a slapi function for checking on shutdowns Fix Description: removed the g_get_shutdown() functions from the plugins, and replaced them with the slapi version Reviewed by: Richm (Thanks!) diff --git a/ldap/servers/plugins/linkedattrs/fixup_task.c b/ldap/servers/plugins/linkedattrs/fixup_task.c index b19d3ab5c..9fa7f6f15 100644 --- a/ldap/servers/plugins/linkedattrs/fixup_task.c +++ b/ldap/servers/plugins/linkedattrs/fixup_task.c @@ -355,7 +355,7 @@ linked_attrs_add_backlinks_callback(Slapi_Entry *e, void *callback_data) int perform_update = 0; Slapi_DN *targetsdn = NULL; - if (g_get_shutdown()) { + if (slapi_is_shutting_down()) { rc = -1; goto done; } diff --git a/ldap/servers/plugins/linkedattrs/linked_attrs.h b/ldap/servers/plugins/linkedattrs/linked_attrs.h index 2eba62f36..d0909cab5 100644 --- a/ldap/servers/plugins/linkedattrs/linked_attrs.h +++ b/ldap/servers/plugins/linkedattrs/linked_attrs.h @@ -138,8 +138,6 @@ int linked_attrs_fixup_task_add(Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Entry *eAfter, int *returncode, char *returntext, void *arg); -int g_get_shutdown(); /* declared in proto-slap.h */ - /* * misc */ diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index c98d8ad00..fc4529d78 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -1670,7 +1670,7 @@ int memberof_get_groups_callback(Slapi_Entry *e, void *callback_data) Slapi_ValueSet *groupvals = *((memberof_get_groups_data*)callback_data)->groupvals; int rc = 0; - if(g_get_shutdown()){ + if(slapi_is_shutting_down()){ rc = -1; goto bail; } diff --git a/ldap/servers/plugins/memberof/memberof.h b/ldap/servers/plugins/memberof/memberof.h index 36901e38d..65398aa7d 100644 --- a/ldap/servers/plugins/memberof/memberof.h +++ b/ldap/servers/plugins/memberof/memberof.h @@ -96,6 +96,4 @@ void memberof_wlock_config(); void memberof_unlock_config(); int memberof_config_get_all_backends(); -int g_get_shutdown(); /* declared in proto-slap.h */ - #endif /* _MEMBEROF_H_ */ diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index eac76a8a4..08bf7711c 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -265,8 +265,6 @@ typedef struct cl5desc typedef void (*VFP)(void *); -int g_get_shutdown(); /* declared in proto-slap.h */ - /***** Global Variables *****/ static CL5Desc s_cl5Desc; @@ -3472,7 +3470,7 @@ static void _cl5TrimFile (Object *obj, long *numToTrim) entry.op = &op; - while ( !finished && !g_get_shutdown() ) + while ( !finished && !slapi_is_shutting_down() ) { it = NULL; count = 0; diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index 6434dbd0c..ccaa29dad 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -50,9 +50,6 @@ #include "csnpl.h" #include "cl5_api.h" -/* from proto-slap.h */ -int g_get_shutdown(); - #define RUV_SAVE_INTERVAL (30 * 1000) /* 30 seconds */ #define START_UPDATE_DELAY 2 /* 2 second */ @@ -2506,7 +2503,7 @@ process_reap_entry (Slapi_Entry *entry, void *cb_data) int rc = -1; /* abort reaping if we've been told to stop or we're shutting down */ - if (*tombstone_reap_stop || g_get_shutdown()) { + if (*tombstone_reap_stop || slapi_is_shutting_down()) { slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, "process_reap_entry: the tombstone reap process " " has been stopped\n"); diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index ca646e91f..8d338c074 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -86,7 +86,6 @@ static struct berval *create_ruv_payload(char *value); static int replica_cleanup_task (Object *r, const char *task_name, char *returntext, int apply_mods); static int replica_task_done(Replica *replica); static multimaster_mtnode_extension * _replica_config_get_mtnode_ext (const Slapi_Entry *e); -int g_get_shutdown(); /* * Note: internal add/modify/delete operations should not be run while @@ -1326,7 +1325,7 @@ replica_cleanallruv_monitor_thread(void *arg) slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "cleanAllRUV_task: Waiting for all the replicas to get cleaned...\n"); - while(!g_get_shutdown()) + while(!slapi_is_shutting_down()) { DS_Sleep(PR_SecondsToInterval(10)); found = 0; diff --git a/ldap/servers/plugins/usn/usn_cleanup.c b/ldap/servers/plugins/usn/usn_cleanup.c index 6f9410e6d..ab6362f69 100644 --- a/ldap/servers/plugins/usn/usn_cleanup.c +++ b/ldap/servers/plugins/usn/usn_cleanup.c @@ -148,7 +148,7 @@ usn_cleanup_thread(void *arg) int opflags = OP_FLAG_TOMBSTONE_ENTRY; /* check for shutdown */ - if(g_get_shutdown()){ + if(slapi_is_shutting_down()){ slapi_task_log_notice(task, "USN tombstone cleanup task aborted due to shutdown."); slapi_task_log_status(task, "USN tombstone cleanup task aborted due to shutdown."); slapi_log_error(SLAPI_LOG_FATAL, USN_PLUGIN_SUBSYSTEM, diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index 2540e25d2..c1e4051da 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -890,6 +890,11 @@ int g_get_shutdown() return slapd_shutdown; } +int slapi_is_shutting_down() +{ + return slapd_shutdown; +} + static int cmd_shutdown; diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index 63c37f027..bad97f89a 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -5301,6 +5301,13 @@ void slapi_ch_array_add( char ***array, char *string ); */ int slapi_ch_array_utf8_inlist(char **array, char *string); +/** + * Check if the server has started shutting down + * + * \return 1 if the server is shutting down + */ +int slapi_is_shutting_down(); + /* * checking routines for allocating and freeing memory */ @@ -6742,7 +6749,20 @@ int slapi_re_exec( Slapi_Regex *re_handle, const char *subject, time_t time_up ) * \warning The regex handler should be released by slapi_re_free(). */ int slapi_re_subs( Slapi_Regex *re_handle, const char *subject, const char *src, char **dst, unsigned long dstlen ); -/* extension to handle search filters properly */ +/** + * Substitutes '&' or '\#' in the param src with the matched string. If the 'src' is a search filter + * do not remove & if it is part of a compound filter. + * + * \param re_handle The regex handler returned from slapi_re_comp. + * \param subject A string checked against the compiled pattern. + * \param src A given string which could contain the substitution symbols. + * \param dst A pointer pointing to the memory which stores the output string. + * \param dstlen Size of the memory dst. + * \param filter Set to 1 if the src is a ldap search filter + * \return This function returns 1 if the substitution was successful. + * \return This function returns 0 if the substitution failed. + * \warning The regex handler should be released by slapi_re_free(). + */ int slapi_re_subs_ext( Slapi_Regex *re_handle, const char *subject, const char *src, char **dst, unsigned long dstlen, int filter ); /** * Releases the regex handler which was returned from slapi_re_comp.
0
a7766ffb1064250714521c7d5531b61561598508
389ds/389-ds-base
Issue 4324 - Some architectures the cache line size file does not exist Bug Description: When optimizing our mutexes we check for a system called coherency_line_size that contains the size value, but if the file did not exist the server would crash in PR_Read (NULL pointer for fd). Fix Description: Check PR_Open() was successfully before calling PR_Read(). Relates: https://github.com/389ds/389-ds-base/issues/4324 Reviewed by: tbordaz(Thanks!)
commit a7766ffb1064250714521c7d5531b61561598508 Author: Mark Reynolds <[email protected]> Date: Fri Feb 12 12:19:09 2021 -0500 Issue 4324 - Some architectures the cache line size file does not exist Bug Description: When optimizing our mutexes we check for a system called coherency_line_size that contains the size value, but if the file did not exist the server would crash in PR_Read (NULL pointer for fd). Fix Description: Check PR_Open() was successfully before calling PR_Read(). Relates: https://github.com/389ds/389-ds-base/issues/4324 Reviewed by: tbordaz(Thanks!) diff --git a/ldap/servers/slapd/ch_malloc.c b/ldap/servers/slapd/ch_malloc.c index cd55d4643..4262b94b5 100644 --- a/ldap/servers/slapd/ch_malloc.c +++ b/ldap/servers/slapd/ch_malloc.c @@ -350,29 +350,37 @@ slapi_ct_memcmp(const void *p1, const void *p2, size_t n) return result; } -#define SYS_CACHELINE_SIZE "/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size" +#define SYS_CACHELINE_SIZE_FILE "/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size" +#define CPU_CACHE_LINE_SZ_DEFAULT 64 static size_t cache_line_size() { PRFileDesc *prfd; char buf[10] = {0}; - size_t i = 0; - - prfd = PR_Open(SYS_CACHELINE_SIZE, PR_RDONLY, SLAPD_DEFAULT_FILE_MODE); - if (PR_Read(prfd, buf, sizeof (buf)) < 0) { - slapi_log_err(SLAPI_LOG_ERR, "cache_line_size", "Can not read %s\n", SYS_CACHELINE_SIZE); + size_t size = 0; + + prfd = PR_Open(SYS_CACHELINE_SIZE_FILE, PR_RDONLY, SLAPD_DEFAULT_FILE_MODE); + if (prfd == NULL) { + /* This architecture does not have a size file, just use the default */ + return CPU_CACHE_LINE_SZ_DEFAULT; + } else if (PR_Read(prfd, buf, sizeof (buf)) < 0) { + slapi_log_err(SLAPI_LOG_NOTICE, "cache_line_size", + "Can not read %s, using cache line size %d\n", + SYS_CACHELINE_SIZE_FILE, CPU_CACHE_LINE_SZ_DEFAULT); PR_Close(prfd); - goto done; + return CPU_CACHE_LINE_SZ_DEFAULT; } PR_Close(prfd); - i = atoi(buf); -done: - if ((i == 0) || (i > 64)) { - slapi_log_err(SLAPI_LOG_INFO, "cache_line_size", "unexpected cpu cache line size => assign 64\n"); - i = 64; + size = atoi(buf); + if (size == 0 || size > CPU_CACHE_LINE_SZ_DEFAULT) { + slapi_log_err(SLAPI_LOG_INFO, "cache_line_size", + "unexpected cpu cache line size => assigning %d\n", + CPU_CACHE_LINE_SZ_DEFAULT); + size = CPU_CACHE_LINE_SZ_DEFAULT; } - return i; + + return size; } pthread_mutex_t*
0
7d2f95dc505626be29fea3aae57695bb9b0defdb
389ds/389-ds-base
Issue 4243 - Fix test: SyncRepl plugin provides a wrong cookie (#4466) (#4466) Bug description: Individual testcase run fine but they fails when run in a raw Fix description: Each testcase needs to do cleanup (at the end) or make initialization more robust relates: https://github.com/389ds/389-ds-base/issues/4243 Reviewed by: William Brown, Simon Pichugin (Thanks !) Platforms tested: F31
commit 7d2f95dc505626be29fea3aae57695bb9b0defdb Author: tbordaz <[email protected]> Date: Tue Dec 1 15:15:21 2020 +0100 Issue 4243 - Fix test: SyncRepl plugin provides a wrong cookie (#4466) (#4466) Bug description: Individual testcase run fine but they fails when run in a raw Fix description: Each testcase needs to do cleanup (at the end) or make initialization more robust relates: https://github.com/389ds/389-ds-base/issues/4243 Reviewed by: William Brown, Simon Pichugin (Thanks !) Platforms tested: F31 diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py index 7b35537d5..75be85e60 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py @@ -30,6 +30,85 @@ pytestmark = pytest.mark.tier1 log = logging.getLogger(__name__) [email protected](scope="function") +def init_sync_repl_plugins(topology, request): + """Prepare test environment (retroCL/sync_repl/ + automember/memberof) and cleanup at the end of the test + 1.: enable retroCL + 2.: configure retroCL to log nsuniqueid as targetUniqueId + 3.: enable content_sync plugin + 4.: enable automember + 5.: create (2) groups. Few groups can help to reproduce the concurrent updates problem. + 6.: configure automember to provision those groups with 'member' + 7.: enable and configure memberof plugin + 8.: enable plugin log level + 9.: restart the server + """ + inst = topology[0] + inst.restart() + + # Enable/configure retroCL + plugin = RetroChangelogPlugin(inst) + plugin.disable() + plugin.enable() + plugin.set('nsslapd-attribute', 'nsuniqueid:targetuniqueid') + + # Enable sync plugin + plugin = ContentSyncPlugin(inst) + plugin.enable() + + # Enable automember + plugin = AutoMembershipPlugin(inst) + plugin.disable() + plugin.enable() + + # Add the automember group + groups = Groups(inst, DEFAULT_SUFFIX) + group = [] + for i in range(1,5): + group.append(groups.create(properties={'cn': 'group%d' % i})) + + # Add the automember config entry + am_configs = AutoMembershipDefinitions(inst) + am_configs_cleanup = [] + for g in group: + am_config = am_configs.create(properties={'cn': 'config %s' % g.get_attr_val_utf8('cn'), + 'autoMemberScope': DEFAULT_SUFFIX, + 'autoMemberFilter': 'uid=*', + 'autoMemberDefaultGroup': g.dn, + 'autoMemberGroupingAttr': 'member:dn'}) + am_configs_cleanup.append(am_config) + + # Enable and configure memberof plugin + plugin = MemberOfPlugin(inst) + plugin.disable() + plugin.enable() + + plugin.replace_groupattr('member') + + memberof_config = MemberOfSharedConfig(inst, 'cn=memberOf config,{}'.format(DEFAULT_SUFFIX)) + try: + memberof_config.create(properties={'cn': 'memberOf config', + 'memberOfGroupAttr': 'member', + 'memberOfAttr': 'memberof'}) + except ldap.ALREADY_EXISTS: + pass + + # Enable plugin log level (usefull for debug) + inst.setLogLevel(65536) + inst.restart() + + def fin(): + inst.restart() + for am_config in am_configs_cleanup: + am_config.delete() + for g in group: + try: + g.delete() + except: + pass + request.addfinalizer(fin) + def test_syncrepl_basic(topology): """ Test basic functionality of the SyncRepl interface @@ -233,88 +312,27 @@ def test_sync_repl_mep(topology, request): sync_repl.join() log.info('test_sync_repl_map: PASS\n') -def test_sync_repl_cookie(topology, request): +def test_sync_repl_cookie(topology, init_sync_repl_plugins, request): """Test sync_repl cookie are progressing is an increasing order when there are nested updates :id: d7fbde25-5702-46ac-b38e-169d7a68e97c :setup: Standalone Instance :steps: - 1.: enable retroCL - 2.: configure retroCL to log nsuniqueid as targetUniqueId - 3.: enable content_sync plugin - 4.: enable automember - 5.: create (2) groups. Few groups can help to reproduce the concurrent updates problem. - 6.: configure automember to provision those groups with 'member' - 7.: enable and configure memberof plugin - 8.: enable plugin log level - 9.: restart the server - 10.: create a thread dedicated to run a sync repl client - 11.: Create (9) users that will generate nested updates (automember/memberof) - 12.: stop sync repl client and collect the list of cookie.change_no - 13.: check that cookies.change_no are in increasing order + 1.: initialization/cleanup done by init_sync_repl_plugins fixture + 2.: create a thread dedicated to run a sync repl client + 3.: Create (9) users that will generate nested updates (automember/memberof) + 4.: stop sync repl client and collect the list of cookie.change_no + 5.: check that cookies.change_no are in increasing order :expectedresults: 1.: succeeds 2.: succeeds 3.: succeeds 4.: succeeds 5.: succeeds - 6.: succeeds - 7.: succeeds - 8.: succeeds - 9.: succeeds - 10.: succeeds - 11.: succeeds - 12.: succeeds - 13.: succeeds """ inst = topology[0] - # Enable/configure retroCL - plugin = RetroChangelogPlugin(inst) - plugin.disable() - plugin.enable() - plugin.set('nsslapd-attribute', 'nsuniqueid:targetuniqueid') - - # Enable sync plugin - plugin = ContentSyncPlugin(inst) - plugin.enable() - - # Enable automember - plugin = AutoMembershipPlugin(inst) - plugin.disable() - plugin.enable() - - # Add the automember group - groups = Groups(inst, DEFAULT_SUFFIX) - group = [] - for i in range(1,3): - group.append(groups.create(properties={'cn': 'group%d' % i})) - - # Add the automember config entry - am_configs = AutoMembershipDefinitions(inst) - for g in group: - am_config = am_configs.create(properties={'cn': 'config %s' % g.get_attr_val_utf8('cn'), - 'autoMemberScope': DEFAULT_SUFFIX, - 'autoMemberFilter': 'uid=*', - 'autoMemberDefaultGroup': g.dn, - 'autoMemberGroupingAttr': 'member:dn'}) - - # Enable and configure memberof plugin - plugin = MemberOfPlugin(inst) - plugin.disable() - plugin.enable() - - plugin.replace_groupattr('member') - - memberof_config = MemberOfSharedConfig(inst, 'cn=memberOf config,{}'.format(DEFAULT_SUFFIX)) - memberof_config.create(properties={'cn': 'memberOf config', - 'memberOfGroupAttr': 'member', - 'memberOfAttr': 'memberof'}) - # Enable plugin log level (usefull for debug) - inst.setLogLevel(65536) - inst.restart() - # create a sync repl client and wait 5 seconds to be sure it is running sync_repl = Sync_persist(inst) sync_repl.start() @@ -335,11 +353,11 @@ def test_sync_repl_cookie(topology, request): # checking that the cookie are in increasing and in an acceptable range (0..1000) assert len(cookies) > 0 - prev = 0 + prev = -1 for cookie in cookies: log.info('Check cookie %s' % cookie) - assert int(cookie) > 0 + assert int(cookie) >= 0 assert int(cookie) < 1000 assert int(cookie) > prev prev = int(cookie) @@ -353,37 +371,24 @@ def test_sync_repl_cookie(topology, request): user.delete() except: pass - for g in group: - try: - g.delete() - except: - pass request.addfinalizer(fin) return -def test_sync_repl_cookie_add_del(topology, request): +def test_sync_repl_cookie_add_del(topology, init_sync_repl_plugins, request): """Test sync_repl cookie are progressing is an increasing order when there add and del :id: 83e11038-6ed0-4a5b-ac77-e44887ab11e3 :setup: Standalone Instance :steps: - 1.: enable retroCL - 2.: configure retroCL to log nsuniqueid as targetUniqueId - 3.: enable content_sync plugin - 4.: enable automember - 5.: create (2) groups. Few groups can help to reproduce the concurrent updates problem. - 6.: configure automember to provision those groups with 'member' - 7.: enable and configure memberof plugin - 8.: enable plugin log level - 9.: restart the server - 10.: create a thread dedicated to run a sync repl client - 11.: Create (3) users that will generate nested updates (automember/memberof) - 12.: Delete (3) users - 13.: stop sync repl client and collect the list of cookie.change_no - 14.: check that cookies.change_no are in increasing order + 1.: initialization/cleanup done by init_sync_repl_plugins fixture + 2.: create a thread dedicated to run a sync repl client + 3.: Create (3) users that will generate nested updates (automember/memberof) + 4.: Delete (3) users + 5.: stop sync repl client and collect the list of cookie.change_no + 6.: check that cookies.change_no are in increasing order :expectedresults: 1.: succeeds 2.: succeeds @@ -391,62 +396,9 @@ def test_sync_repl_cookie_add_del(topology, request): 4.: succeeds 5.: succeeds 6.: succeeds - 7.: succeeds - 8.: succeeds - 9.: succeeds - 10.: succeeds - 11.: succeeds - 12.: succeeds - 13.: succeeds - 14.: succeeds """ inst = topology[0] - # Enable/configure retroCL - plugin = RetroChangelogPlugin(inst) - plugin.disable() - plugin.enable() - plugin.set('nsslapd-attribute', 'nsuniqueid:targetuniqueid') - - # Enable sync plugin - plugin = ContentSyncPlugin(inst) - plugin.enable() - - # Enable automember - plugin = AutoMembershipPlugin(inst) - plugin.disable() - plugin.enable() - - # Add the automember group - groups = Groups(inst, DEFAULT_SUFFIX) - group = [] - for i in range(1,3): - group.append(groups.create(properties={'cn': 'group%d' % i})) - - # Add the automember config entry - am_configs = AutoMembershipDefinitions(inst) - for g in group: - am_config = am_configs.create(properties={'cn': 'config %s' % g.get_attr_val_utf8('cn'), - 'autoMemberScope': DEFAULT_SUFFIX, - 'autoMemberFilter': 'uid=*', - 'autoMemberDefaultGroup': g.dn, - 'autoMemberGroupingAttr': 'member:dn'}) - - # Enable and configure memberof plugin - plugin = MemberOfPlugin(inst) - plugin.disable() - plugin.enable() - - plugin.replace_groupattr('member') - - memberof_config = MemberOfSharedConfig(inst, 'cn=memberOf config,{}'.format(DEFAULT_SUFFIX)) - memberof_config.create(properties={'cn': 'memberOf config', - 'memberOfGroupAttr': 'member', - 'memberOfAttr': 'memberof'}) - # Enable plugin log level (usefull for debug) - inst.setLogLevel(65536) - inst.restart() - # create a sync repl client and wait 5 seconds to be sure it is running sync_repl = Sync_persist(inst) sync_repl.start() @@ -482,107 +434,43 @@ def test_sync_repl_cookie_add_del(topology, request): log.info('test_sync_repl_cookie_add_del: PASS\n') def fin(): - inst.restart() - for g in group: - try: - g.delete() - except: - pass + pass request.addfinalizer(fin) return -def test_sync_repl_cookie_with_failure(topology, request): +def test_sync_repl_cookie_with_failure(topology, init_sync_repl_plugins, request): """Test sync_repl cookie are progressing is the right order when there is a failure in nested updates :id: e0103448-170e-4080-8f22-c34606447ce2 :setup: Standalone Instance :steps: - 1.: enable retroCL - 2.: configure retroCL to log nsuniqueid as targetUniqueId - 3.: enable content_sync plugin - 4.: enable automember - 5.: create (4) groups. - make group2 groupOfUniqueNames so the automember - will fail to add 'member' (uniqueMember expected) - 6.: configure automember to provision those groups with 'member' - 7.: enable and configure memberof plugin - 8.: enable plugin log level - 9.: restart the server - 10.: create a thread dedicated to run a sync repl client - 11.: Create a group that will be the only update received by sync repl client - 12.: Create (9) users that will generate nested updates (automember/memberof) - 13.: stop sync repl client and collect the list of cookie.change_no - 14.: check that the list of cookie.change_no contains only the group 'step 11' + 1.: initialization/cleanup done by init_sync_repl_plugins fixture + 2.: update group2 so that it will not accept 'member' attribute (set by memberof) + 3.: create a thread dedicated to run a sync repl client + 4.: Create a group that will be the only update received by sync repl client + 5.: Create (9) users that will generate nested updates (automember/memberof). + creation will fail because 'member' attribute is not allowed in group2 + 6.: stop sync repl client and collect the list of cookie.change_no + 7.: check that the list of cookie.change_no contains only the group 'step 11' :expectedresults: 1.: succeeds 2.: succeeds 3.: succeeds 4.: succeeds - 5.: succeeds + 5.: Fails (expected) 6.: succeeds 7.: succeeds - 8.: succeeds - 9.: succeeds - 10.: succeeds - 11.: succeeds - 12.: Fails (expected) - 13.: succeeds - 14.: succeeds """ inst = topology[0] - # Enable/configure retroCL - plugin = RetroChangelogPlugin(inst) - plugin.disable() - plugin.enable() - plugin.set('nsslapd-attribute', 'nsuniqueid:targetuniqueid') - - # Enable sync plugin - plugin = ContentSyncPlugin(inst) - plugin.enable() - - # Enable automember - plugin = AutoMembershipPlugin(inst) - plugin.disable() - plugin.enable() - - # Add the automember group - groups = Groups(inst, DEFAULT_SUFFIX) - group = [] - for i in range(1,5): - group.append(groups.create(properties={'cn': 'group%d' % i})) - # Set group2 as a groupOfUniqueNames so that automember will fail to update that group # This will trigger a failure in internal MOD and a failure to add member - group[1].replace('objectclass', 'groupOfUniqueNames') + group2 = Groups(inst, DEFAULT_SUFFIX).get('group2') + group2.replace('objectclass', 'groupOfUniqueNames') - # Add the automember config entry - am_configs = AutoMembershipDefinitions(inst) - for g in group: - am_config = am_configs.create(properties={'cn': 'config %s' % g.get_attr_val_utf8('cn'), - 'autoMemberScope': DEFAULT_SUFFIX, - 'autoMemberFilter': 'uid=*', - 'autoMemberDefaultGroup': g.dn, - 'autoMemberGroupingAttr': 'member:dn'}) - - # Enable and configure memberof plugin - plugin = MemberOfPlugin(inst) - plugin.disable() - plugin.enable() - - plugin.replace_groupattr('member') - - memberof_config = MemberOfSharedConfig(inst, 'cn=memberOf config,{}'.format(DEFAULT_SUFFIX)) - memberof_config.create(properties={'cn': 'memberOf config', - 'memberOfGroupAttr': 'member', - 'memberOfAttr': 'memberof'}) - - # Enable plugin log level (usefull for debug) - inst.setLogLevel(65536) - inst.restart() # create a sync repl client and wait 5 seconds to be sure it is running sync_repl = Sync_persist(inst) @@ -590,7 +478,8 @@ def test_sync_repl_cookie_with_failure(topology, request): time.sleep(5) # Add a test group just to check that sync_repl receives that SyncControlInfo cookie - group.append(groups.create(properties={'cn': 'group%d' % 10})) + groups = Groups(inst, DEFAULT_SUFFIX) + testgroup = groups.create(properties={'cn': 'group%d' % 10}) # create users, that automember/memberof will generate nested updates users = UserAccounts(inst, DEFAULT_SUFFIX) @@ -632,10 +521,6 @@ def test_sync_repl_cookie_with_failure(topology, request): user.delete() except: pass - for g in group: - try: - g.delete() - except: - pass + testgroup.delete() request.addfinalizer(fin)
0
500e8be08158634526a92791f283c3ee210a279a
389ds/389-ds-base
Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13049 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for be. modified: retrocl_postob in retrocl_po.c
commit 500e8be08158634526a92791f283c3ee210a279a Author: Noriko Hosoi <[email protected]> Date: Tue Feb 24 17:20:35 2015 -0800 Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13049 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for be. modified: retrocl_postob in retrocl_po.c diff --git a/ldap/servers/plugins/retrocl/retrocl_po.c b/ldap/servers/plugins/retrocl/retrocl_po.c index 9128fef1e..bcf53cd28 100644 --- a/ldap/servers/plugins/retrocl/retrocl_po.c +++ b/ldap/servers/plugins/retrocl/retrocl_po.c @@ -597,6 +597,10 @@ int retrocl_postob (Slapi_PBlock *pb, int optype) */ (void)slapi_pblock_get( pb, SLAPI_BACKEND, &be ); + if (be == NULL) { + LDAPDebug0Args(LDAP_DEBUG_ANY, "retrocl_postob: backend is not set\n"); + return SLAPI_PLUGIN_FAILURE; + } if (slapi_be_logchanges(be) == 0) { LDAPDebug0Args(LDAP_DEBUG_TRACE,"not applying change if not logging\n");
0
e09d984add34dc06250d0a3a3bd96c8d8b1ff9e1
389ds/389-ds-base
Issue 5239 - Nightly copr builds are broken Bug Description: Nightly builds started to fail during srpm generation step `copr-rpmbuild` executes mock with `mock-source-build.cfg` config that drops a lot of capabilities, including CAP_SETUID and CAP_SETGID, used by npm. From https://github.com/npm/cli/blob/latest/changelogs/CHANGELOG-7.md#all-lifecycle-scripts > The user, group, uid, gid, and unsafe-perms configurations are > no longer relevant. When npm is run as root, scripts are always > run with the effective uid and gid of the working directory owner. Files had `root:mockbuild` ownership, and `npm` was running under root, so `npm` tried to set gid to `mockbuild` user and was denied. Fix Description: We should always chown files in $CWD to `root:root` since the `make srpm` step is executed under root user. Fixes: https://github.com/389ds/389-ds-base/issues/5239 Reviewed by: @mreynolds389 (Thanks!)
commit e09d984add34dc06250d0a3a3bd96c8d8b1ff9e1 Author: Viktor Ashirov <[email protected]> Date: Mon Mar 28 13:10:20 2022 +0200 Issue 5239 - Nightly copr builds are broken Bug Description: Nightly builds started to fail during srpm generation step `copr-rpmbuild` executes mock with `mock-source-build.cfg` config that drops a lot of capabilities, including CAP_SETUID and CAP_SETGID, used by npm. From https://github.com/npm/cli/blob/latest/changelogs/CHANGELOG-7.md#all-lifecycle-scripts > The user, group, uid, gid, and unsafe-perms configurations are > no longer relevant. When npm is run as root, scripts are always > run with the effective uid and gid of the working directory owner. Files had `root:mockbuild` ownership, and `npm` was running under root, so `npm` tried to set gid to `mockbuild` user and was denied. Fix Description: We should always chown files in $CWD to `root:root` since the `make srpm` step is executed under root user. Fixes: https://github.com/389ds/389-ds-base/issues/5239 Reviewed by: @mreynolds389 (Thanks!) diff --git a/.copr/Makefile b/.copr/Makefile index 2c18f2230..d575880fa 100644 --- a/.copr/Makefile +++ b/.copr/Makefile @@ -6,6 +6,13 @@ srpm: # Install build dependencies dnf install -y dnf-plugins-core dnf builddep -y --skip-broken --spec rpmbuild/SPECS/389-ds-base.spec --best --allowerasing --setopt=install_weak_deps=False + # chown files in current working directory to root:root + # because when npm is run as root, scripts are always run + # with the effective uid and gid of the working directory owner. + # copr-rpmbuild runs mock with CAP_SETUID and CAP_SETGID + # capabilities dropped, and build commands are executed as root. + # So npm fails if current working directory is not owned by root. + chown -R root:root . # Generate srpm SKIP_AUDIT_CI=1 make -f rpm.mk srpms
0
e92d2165463afe7a7606af6d13532642fa3462c1
389ds/389-ds-base
Coverity fix - 11952 Fix resource leak in linked-attributes fixup task
commit e92d2165463afe7a7606af6d13532642fa3462c1 Author: Mark Reynolds <[email protected]> Date: Mon Sep 16 09:48:05 2013 -0400 Coverity fix - 11952 Fix resource leak in linked-attributes fixup task diff --git a/ldap/servers/plugins/linkedattrs/fixup_task.c b/ldap/servers/plugins/linkedattrs/fixup_task.c index 537544d00..ff6dd82ea 100644 --- a/ldap/servers/plugins/linkedattrs/fixup_task.c +++ b/ldap/servers/plugins/linkedattrs/fixup_task.c @@ -236,6 +236,7 @@ linked_attrs_fixup_links(struct configEntry *config) if (plugin_is_betxn) { Slapi_DN *fixup_dn = slapi_sdn_new_dn_byref(config->scope); Slapi_Backend *be = slapi_be_select(fixup_dn); + slapi_sdn_free(&fixup_dn); if (be) { fixup_pb = slapi_pblock_new();
0
d41ef935b98811ab715018900b08c9891d3351e6
389ds/389-ds-base
Issue 50627 - Add ASAN logs to HTML report Bug Description: ASAN-enabled server generates error logs, it would be nice to collect them and identify tests that caused the error. Fix Description: Add a hook for pytest-html plugin to add logs generated by ASAN to the html report. After test is done, these logs will be rotated. Fixes: https://pagure.io/389-ds-base/issue/50627 Reviewed by: mreynolds (Thanks!)
commit d41ef935b98811ab715018900b08c9891d3351e6 Author: Viktor Ashirov <[email protected]> Date: Wed Sep 25 21:18:24 2019 +0200 Issue 50627 - Add ASAN logs to HTML report Bug Description: ASAN-enabled server generates error logs, it would be nice to collect them and identify tests that caused the error. Fix Description: Add a hook for pytest-html plugin to add logs generated by ASAN to the html report. After test is done, these logs will be rotated. Fixes: https://pagure.io/389-ds-base/issue/50627 Reviewed by: mreynolds (Thanks!) diff --git a/dirsrvtests/conftest.py b/dirsrvtests/conftest.py index 70a6d5ac8..8c0d65feb 100644 --- a/dirsrvtests/conftest.py +++ b/dirsrvtests/conftest.py @@ -1,12 +1,15 @@ import subprocess import logging import pytest +import shutil +import glob import os from lib389.paths import Paths from enum import Enum pkgs = ['389-ds-base', 'nss', 'nspr', 'openldap', 'cyrus-sasl'] +p = Paths() class FIPSState(Enum): ENABLED = 'enabled' @@ -62,19 +65,8 @@ def pytest_report_header(config): return header [email protected] -def pytest_html_results_table_header(cells): - cells.pop() - - [email protected] -def pytest_html_results_table_row(report, cells): - cells.pop() - - @pytest.fixture(scope="function", autouse=True) def log_test_name_to_journald(request): - p = Paths() if p.with_systemd: def log_current_test(): subprocess.Popen("echo $PYTEST_CURRENT_TEST | systemd-cat -t pytest", stdin=subprocess.PIPE, shell=True) @@ -82,3 +74,29 @@ def log_test_name_to_journald(request): log_current_test() request.addfinalizer(log_current_test) return log_test_name_to_journald + + [email protected](scope="function", autouse=True) +def rotate_xsan_logs(request): + if p.asan_enabled: + xsan_logs_dir = f'{p.run_dir}/bak' + if not os.path.exists(xsan_logs_dir): + os.mkdir(xsan_logs_dir) + else: + for f in glob.glob(f'{p.run_dir}/ns-slapd-*san*'): + shutil.move(f, xsan_logs_dir) + return rotate_xsan_logs + + [email protected](hookwrapper=True) +def pytest_runtest_makereport(item, call): + pytest_html = item.config.pluginmanager.getplugin('html') + outcome = yield + report = outcome.get_result() + extra = getattr(report, 'extra', []) + if report.when == 'call': + for f in glob.glob(f'{p.run_dir}/ns-slapd-*san*'): + with open(f) as asan_report: + text = asan_report.read() + extra.append(pytest_html.extras.text(text, name=os.path.basename(f))) + report.extra = extra
0
b0fc82233a5ea929c5fad835f9e825a8f0b97968
389ds/389-ds-base
Ticket #48969 - nsslapd-auditfaillog always has an explicit path Description: commit ef2c3c4cc6f966935dbe367dd0d882ae81de3cc4 introduced a RESOURCE_LEAK. auditlog.c:180: leaked_storage: Variable "audit_config" going out of scope leaks the storage it points to. Reviewed by nhosoi (one line commit rule) (cherry picked from commit 95d820901e7264490bae02b8ca943d09a344d7ac)
commit b0fc82233a5ea929c5fad835f9e825a8f0b97968 Author: Noriko Hosoi <[email protected]> Date: Thu Sep 1 11:34:53 2016 -0700 Ticket #48969 - nsslapd-auditfaillog always has an explicit path Description: commit ef2c3c4cc6f966935dbe367dd0d882ae81de3cc4 introduced a RESOURCE_LEAK. auditlog.c:180: leaked_storage: Variable "audit_config" going out of scope leaks the storage it points to. Reviewed by nhosoi (one line commit rule) (cherry picked from commit 95d820901e7264490bae02b8ca943d09a344d7ac) diff --git a/ldap/servers/slapd/auditlog.c b/ldap/servers/slapd/auditlog.c index 85d136c0e..74d1b4604 100644 --- a/ldap/servers/slapd/auditlog.c +++ b/ldap/servers/slapd/auditlog.c @@ -177,6 +177,7 @@ write_auditfail_log_entry( Slapi_PBlock *pb ) write_audit_file(SLAPD_AUDITFAIL_LOG, operation_get_type(op), dn, change, flag, curtime, pbrc, SLAPD_AUDITFAIL_LOG); } slapi_ch_free_string(&auditfail_config); + slapi_ch_free_string(&audit_config); }
0
9bf0fc293b4c0d89f51a3b74fd77d6448c65c02d
389ds/389-ds-base
Issue 50474 - Unify result codes for add and modify of repl5 config Bug Description: Same constraints resulting in error are reported as different LDAP result codes when using different operation for adjusting these. Fix Description: A part of the code had not conveyed the error reason down the stack, therefore adding this information and returning the proper code. Fixes: https://pagure.io/389-ds-base/issue/50474 Author: Matus Honek <[email protected]> Review by: mreynolds, spichugi (thanks!)
commit 9bf0fc293b4c0d89f51a3b74fd77d6448c65c02d Author: Matúš Honěk <[email protected]> Date: Wed Jan 16 09:49:28 2019 +0100 Issue 50474 - Unify result codes for add and modify of repl5 config Bug Description: Same constraints resulting in error are reported as different LDAP result codes when using different operation for adjusting these. Fix Description: A part of the code had not conveyed the error reason down the stack, therefore adding this information and returning the proper code. Fixes: https://pagure.io/389-ds-base/issue/50474 Author: Matus Honek <[email protected]> Review by: mreynolds, spichugi (thanks!) diff --git a/dirsrvtests/tests/suites/replication/replica_config_test.py b/dirsrvtests/tests/suites/replication/replica_config_test.py index 9a0e1b41f..3dc03713a 100644 --- a/dirsrvtests/tests/suites/replication/replica_config_test.py +++ b/dirsrvtests/tests/suites/replication/replica_config_test.py @@ -4,7 +4,6 @@ import copy import os import ldap from lib389._constants import * -from lib389 import Entry from lib389.topologies import topology_st as topo from lib389.replica import Replicas @@ -104,12 +103,14 @@ def agmt_setup(topo): def perform_invalid_create(many, properties, attr, value): my_properties = copy.deepcopy(properties) my_properties[attr] = value - with pytest.raises(ldap.LDAPError): + with pytest.raises(ldap.LDAPError) as ei: many.create(properties=my_properties) + return ei.value def perform_invalid_modify(o, attr, value): - with pytest.raises(ldap.LDAPError): + with pytest.raises(ldap.LDAPError) as ei: o.replace(attr, value) + return ei.value @pytest.mark.parametrize("attr, too_small, too_big, overflow, notnum, valid", repl_add_attrs) def test_replica_num_add(topo, attr, too_small, too_big, overflow, notnum, valid): @@ -254,9 +255,25 @@ def test_agmt_num_modify(topo, attr, too_small, too_big, overflow, notnum, valid # Value is valid agmt.replace(attr, valid) + [email protected] +def test_same_attr_yields_same_return_code(topo): + """Test that various operations with same incorrect attribute value yield same return code + """ + attr = 'nsDS5ReplicaId' + + replica_reset(topo) + replicas = Replicas(topo.standalone) + e = perform_invalid_create(replicas, replica_dict, attr, too_big) + assert type(e) is ldap.UNWILLING_TO_PERFORM + + replica = replica_setup(topo) + e = perform_invalid_modify(replica, attr, too_big) + assert type(e) is ldap.UNWILLING_TO_PERFORM + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode CURRENT_FILE = os.path.realpath(__file__) pytest.main(["-s", CURRENT_FILE]) - diff --git a/ldap/servers/plugins/replication/repl5.h b/ldap/servers/plugins/replication/repl5.h index 138578d5f..1801a333e 100644 --- a/ldap/servers/plugins/replication/repl5.h +++ b/ldap/servers/plugins/replication/repl5.h @@ -662,7 +662,7 @@ Replica *replica_new(const Slapi_DN *root); Replica *windows_replica_new(const Slapi_DN *root); /* this function should be called to construct the replica object during addition of the replica over LDAP */ -Replica *replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation); +int replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation, Replica **r); void replica_destroy(void **arg); int replica_subentry_update(Slapi_DN *repl_root, ReplicaId rid); int replica_subentry_check(Slapi_DN *repl_root, ReplicaId rid); diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index 6a5363e43..b3f03d5c0 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -128,8 +128,9 @@ replica_new(const Slapi_DN *root) e = _replica_get_config_entry(root, NULL); if (e) { errorbuf[0] = '\0'; - r = replica_new_from_entry(e, errorbuf, - PR_FALSE /* not a newly added entry */); + replica_new_from_entry(e, errorbuf, + PR_FALSE, /* not a newly added entry */ + &r); if (NULL == r) { slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_new - " @@ -143,17 +144,17 @@ replica_new(const Slapi_DN *root) } /* constructs the replica object from the newly added entry */ -Replica * -replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) +int +replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation, Replica **rp) { - int rc = 0; Replica *r; + int rc = LDAP_SUCCESS; if (e == NULL) { if (NULL != errortext) { PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, "NULL entry"); } - return NULL; + return LDAP_OTHER; } r = (Replica *)slapi_ch_calloc(1, sizeof(Replica)); @@ -162,7 +163,7 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) if (NULL != errortext) { PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, "Out of memory"); } - rc = -1; + rc = LDAP_OTHER; goto done; } @@ -170,7 +171,7 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) if (NULL != errortext) { PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, "failed to create replica lock"); } - rc = -1; + rc = LDAP_OTHER; goto done; } @@ -178,7 +179,7 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) if (NULL != errortext) { PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, "failed to create replica lock"); } - rc = -1; + rc = LDAP_OTHER; goto done; } @@ -191,14 +192,17 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) /* read parameters from the replica config entry */ rc = _replica_init_from_config(r, e, errortext); - if (rc != 0) { + if (rc != LDAP_SUCCESS) { goto done; } /* configure ruv */ rc = _replica_configure_ruv(r, PR_FALSE); if (rc != 0) { + rc = LDAP_OTHER; goto done; + } else { + rc = LDAP_SUCCESS; } /* If smallest csn exists in RUV for our local replica, it's ok to begin iteration */ @@ -217,8 +221,12 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) * (done by the update state event scheduled below) */ } - if (rc != 0) + if (rc != 0) { + rc = LDAP_OTHER; goto done; + } else { + rc = LDAP_SUCCESS; + } /* ONREPL - the state update can occur before the entry is added to the DIT. In that case the updated would fail but nothing bad would happen. The next @@ -237,11 +245,12 @@ replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_operation) } done: - if (rc != 0 && r) { + if (rc != LDAP_SUCCESS && r) { replica_destroy((void **)&r); } - return r; + *rp = r; + return rc; } @@ -1789,9 +1798,9 @@ _replica_check_validity(const Replica *r) if (r->repl_root == NULL || r->repl_type == 0 || r->repl_rid == 0 || r->repl_csngen == NULL || r->repl_name == NULL) { - return -1; + return LDAP_OTHER; } else { - return 0; + return LDAP_SUCCESS; } } @@ -1841,7 +1850,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) (char *)slapi_entry_get_dn((Slapi_Entry *)e)); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - %s\n", errormsg); - return -1; + return LDAP_OTHER; } r->repl_root = slapi_sdn_new_dn_passin(val); @@ -1851,7 +1860,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, attr_replicaType))) { if (repl_config_valid_num(attr_replicaType, val, 0, REPLICA_TYPE_UPDATABLE, &rc, errormsg, &rtype) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->repl_type = rtype; slapi_ch_free_string(&val); @@ -1867,7 +1876,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaBackoffMin))) { if (repl_config_valid_num(type_replicaBackoffMin, val, 1, INT_MAX, &rc, errormsg, &backoff_min) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } slapi_ch_free_string(&val); } else { @@ -1882,7 +1891,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaBackoffMax))) { if (repl_config_valid_num(type_replicaBackoffMax, val, 1, INT_MAX, &rc, errormsg, &backoff_max) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } slapi_ch_free_string(&val); } else { @@ -1899,7 +1908,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) backoff_min, backoff_max); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - " "%s\n", errormsg); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } else { slapi_counter_set_value(r->backoff_min, backoff_min); slapi_counter_set_value(r->backoff_max, backoff_max); @@ -1910,7 +1919,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaProtocolTimeout))) { if (repl_config_valid_num(type_replicaProtocolTimeout, val, 0, INT_MAX, &rc, errormsg, &ptimeout) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } slapi_ch_free_string(&val); slapi_counter_set_value(r->protocol_timeout, ptimeout); @@ -1926,7 +1935,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaReleaseTimeout))) { if (repl_config_valid_num(type_replicaReleaseTimeout, val, 0, INT_MAX, &rc, errortext, &release_timeout) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } slapi_counter_set_value(r->release_timeout, release_timeout); slapi_ch_free_string(&val); @@ -1950,7 +1959,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) type_replicaPrecisePurge, precise_purging); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - " "%s\n", errormsg); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } slapi_ch_free_string(&precise_purging); } else { @@ -1963,7 +1972,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if((val = slapi_entry_attr_get_charptr(e, attr_flags))) { if (repl_config_valid_num(attr_flags, val, 0, 1, &rc, errortext, &rflags) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->repl_flags = (uint32_t)rflags; slapi_ch_free_string(&val); @@ -1990,7 +1999,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) int64_t rid; if (repl_config_valid_num(attr_replicaId, val, 1, 65534, &rc, errormsg, &rid) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->repl_rid = (ReplicaId)rid; slapi_ch_free_string(&val); @@ -2000,7 +2009,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) attr_replicaId, (char *)slapi_entry_get_dn((Slapi_Entry *)e)); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - %s\n", errormsg); - return -1; + return LDAP_OTHER; } } @@ -2013,7 +2022,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) (char *)slapi_entry_get_dn((Slapi_Entry *)e)); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - %s\n", errormsg); - return -1; + return LDAP_OTHER; } r->repl_csngen = object_new((void *)gen, (FNFree)csngen_free); @@ -2031,7 +2040,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, attr_replicaBindDnGroupCheckInterval))) { if (repl_config_valid_num(attr_replicaBindDnGroupCheckInterval, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->updatedn_group_check_interval = interval; slapi_ch_free_string(&val); @@ -2051,7 +2060,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) (char *)slapi_entry_get_dn((Slapi_Entry *)e), rc); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - %s\n", errormsg); - return -1; + return LDAP_OTHER; } else r->new_name = PR_TRUE; } @@ -2072,7 +2081,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaPurgeDelay))) { if (repl_config_valid_num(type_replicaPurgeDelay, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->repl_purge_delay = interval; slapi_ch_free_string(&val); @@ -2083,7 +2092,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) if ((val = slapi_entry_attr_get_charptr(e, type_replicaTombstonePurgeInterval))) { if (repl_config_valid_num(type_replicaTombstonePurgeInterval, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { slapi_ch_free_string(&val); - return -1; + return LDAP_UNWILLING_TO_PERFORM; } r->tombstone_reap_interval = interval; slapi_ch_free_string(&val); diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index 7649aa14e..749e90936 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -267,9 +267,8 @@ replica_config_add(Slapi_PBlock *pb __attribute__((unused)), } /* create replica object */ - r = replica_new_from_entry(e, errortext, PR_TRUE /* is a newly added entry */); + *returncode = replica_new_from_entry(e, errortext, PR_TRUE /* is a newly added entry */, &r); if (r == NULL) { - *returncode = LDAP_OPERATIONS_ERROR; goto done; }
0
45af34013f8bdd34f939d36b16776413e13c0a51
389ds/389-ds-base
Issue 5254 - dscreate create-template regression due to 5a3bdc336 (#5255) dscreate create-template regression due to 829ea4113..5a3bdc336 (default value for template_file parameter was unwillingly changed to 'None' (instead of None)) Issue: 5254 https://github.com/389ds/389-ds-base/issues/5254 Reviewed by:
commit 45af34013f8bdd34f939d36b16776413e13c0a51 Author: progier389 <[email protected]> Date: Mon Apr 11 16:15:07 2022 +0200 Issue 5254 - dscreate create-template regression due to 5a3bdc336 (#5255) dscreate create-template regression due to 829ea4113..5a3bdc336 (default value for template_file parameter was unwillingly changed to 'None' (instead of None)) Issue: 5254 https://github.com/389ds/389-ds-base/issues/5254 Reviewed by: diff --git a/src/lib389/cli/dscreate b/src/lib389/cli/dscreate index 0b41166cc..aa3878ff9 100755 --- a/src/lib389/cli/dscreate +++ b/src/lib389/cli/dscreate @@ -51,7 +51,7 @@ interactive_parser.set_defaults(func=cli_instance.instance_create_interactive) template_parser = subparsers.add_parser('create-template', help="Display an example inf answer file, or provide a file name to write it to disk.") template_parser.add_argument('--advanced', action='store_true', default=False, help="Add advanced options to the template - changing the advanced options may make your instance install fail") -template_parser.add_argument('template_file', nargs="?", default='None', help="Write example template to this file") +template_parser.add_argument('template_file', nargs="?", default=None, help="Write example template to this file") template_parser.set_defaults(func=cli_instance.instance_example) subtree_parser = subparsers.add_parser('ds-root', help="Prepare a root directory in which non root user can create, run and administer instances.")
0
2fa85dee583f21337c941bbd76ae86fab621766a
389ds/389-ds-base
Bug: 334561 Description: Clean up spec file for RPM build Fix Description: Make the spec files use the conventions used by the Fedora/Red Hat packaging system
commit 2fa85dee583f21337c941bbd76ae86fab621766a Author: richm%stanfordalumni.org <richm%stanfordalumni.org> Date: Thu May 11 14:51:02 2006 +0000 Bug: 334561 Description: Clean up spec file for RPM build Fix Description: Make the spec files use the conventions used by the Fedora/Red Hat packaging system diff --git a/build_svrcore-devel_rpm b/build_svrcore-devel_rpm new file mode 100644 index 000000000..484b0a460 --- /dev/null +++ b/build_svrcore-devel_rpm @@ -0,0 +1,249 @@ +#!/bin/sh +# ***** BEGIN LICENSE BLOCK ***** +# Version: MPL 1.1/GPL 2.0/LGPL 2.1 +# +# The contents of this file are subject to the Mozilla Public License Version +# 1.1 (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# http://www.mozilla.org/MPL/ +# +# Software distributed under the License is distributed on an "AS IS" basis, +# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +# for the specific language governing rights and limitations under the +# License. +# +# The Original Code is the Netscape svrcore library. +# +# The Initial Developer of the Original Code is +# Red Hat +# Portions created by the Initial Developer are Copyright (C) 2006 +# the Initial Developer. All Rights Reserved. +# +# Contributor(s): Rich Megginson <[email protected]> +# +# Alternatively, the contents of this file may be used under the terms of +# either the GNU General Public License Version 2 or later (the "GPL"), or +# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +# in which case the provisions of the GPL or the LGPL are applicable instead +# of those above. If you wish to allow use of your version of this file only +# under the terms of either the GPL or the LGPL, and not to allow others to +# use your version of this file under the terms of the MPL, indicate your +# decision by deleting the provisions above and replace them with the notice +# and other provisions required by the GPL or the LGPL. If you do not delete +# the provisions above, a recipient may use your version of this file under +# the terms of any one of the MPL, the GPL or the LGPL. +# +# ***** END LICENSE BLOCK ***** +# This script can be used to build the svrcore-devel rpm and srpm. It assumes +# you begin with nothing but this script. You must have nspr, nspr-devel, +# nss, and nss-devel installed on your system in order to run this script. Not +# only will the script check, but the rpmbuild will also check and bomb out if +# those dependencies are not present. The script allows you to build the rpm +# as a non root user and puts the build files under the current directory. This +# script does not install the rpm. +# +# You may need to edit this script to change: +# the versions of nspr and nss used +# the CVS tag for pulling svrcore +# the svrcore version and release - these should match the spec file + +# Always switch into the base directory of this +# shell script prior to executing it so that all +# of its output is written to this directory +cd `dirname $0` + +# This script may ONLY be run on Linux! +OS=`uname` +if [ ${OS} != "Linux" ]; then + echo "The '$0' script is ONLY executable on a 'Linux' machine!" + exit 255 +fi + +# This script may ONLY be executed on either +# an 'i386' platform or an 'x86_64' platform! +PLATFORM=`uname -i` +if [ ${PLATFORM} = "i386" ]; then + # define NSS variables unique to this script + BITSIZE=32-bit + NSPR_BUILDTIME_DEPENDENCY="nspr-4.6-1.i386" + NSPR_DEVEL_BUILDTIME_DEPENDENCY="nspr-devel-4.6-1.i386" + NSS_BUILDTIME_DEPENDENCY="nss-3.11-1.i386" + NSS_DEVEL_BUILDTIME_DEPENDENCY="nss-devel-3.11-1.i386" +elif [ ${PLATFORM} = "x86_64" ]; then + # define NSS variables unique to this script + BITSIZE=64-bit + NSPR_BUILDTIME_DEPENDENCY="nspr-4.6-1.x86_64" + NSPR_DEVEL_BUILDTIME_DEPENDENCY="nspr-devel-4.6-1.x86_64" + NSS_BUILDTIME_DEPENDENCY="nss-3.11-1.x86_64" + NSS_DEVEL_BUILDTIME_DEPENDENCY="nss-devel-3.11-1.x86_64" +else + echo "The '$0' script is ONLY executable on either" + echo "an 'i386' platform or an 'x86_64' platform!" + exit 255 +fi + +# initialize environment variables for this script +unset LD_LIBRARY_PATH + +CVSROOT=:pserver:[email protected]:/cvsroot +export CVSROOT + +# Check Build Requirements: +# +# This script requires that the associated ${BITSIZE} NSPR +# packages are installed on the system PRIOR to execution! +# +echo "Checking that ALL ${BITSIZE} Buildtime Dependencies are present . . ." +BUILDTIME_DEPENDENCIES=0 +TOTAL_BUILDTIME_DEPENDENCIES=4 +RPM_PRESENCE=`rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' ${NSPR_BUILDTIME_DEPENDENCY}` +if [ "${RPM_PRESENCE}" != "${NSPR_BUILDTIME_DEPENDENCY}" ]; then + echo " Missing '${NSPR_BUILDTIME_DEPENDENCY}'!" +else + echo " Found '${NSPR_BUILDTIME_DEPENDENCY}'!" + BUILDTIME_DEPENDENCIES=`expr ${BUILDTIME_DEPENDENCIES} + 1` +fi +RPM_PRESENCE=`rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' ${NSPR_DEVEL_BUILDTIME_DEPENDENCY}` +if [ "${RPM_PRESENCE}" != "${NSPR_DEVEL_BUILDTIME_DEPENDENCY}" ]; then + echo " Missing '${NSPR_DEVEL_BUILDTIME_DEPENDENCY}'!" +else + echo " Found '${NSPR_DEVEL_BUILDTIME_DEPENDENCY}'!" + BUILDTIME_DEPENDENCIES=`expr ${BUILDTIME_DEPENDENCIES} + 1` +fi +RPM_PRESENCE=`rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' ${NSS_BUILDTIME_DEPENDENCY}` +if [ "${RPM_PRESENCE}" != "${NSS_BUILDTIME_DEPENDENCY}" ]; then + echo " Missing '${NSS_BUILDTIME_DEPENDENCY}'!" +else + echo " Found '${NSS_BUILDTIME_DEPENDENCY}'!" + BUILDTIME_DEPENDENCIES=`expr ${BUILDTIME_DEPENDENCIES} + 1` +fi +RPM_PRESENCE=`rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' ${NSS_DEVEL_BUILDTIME_DEPENDENCY}` +if [ "${RPM_PRESENCE}" != "${NSS_DEVEL_BUILDTIME_DEPENDENCY}" ]; then + echo " Missing '${NSS_DEVEL_BUILDTIME_DEPENDENCY}'!" +else + echo " Found '${NSS_DEVEL_BUILDTIME_DEPENDENCY}'!" + BUILDTIME_DEPENDENCIES=`expr ${BUILDTIME_DEPENDENCIES} + 1` +fi +if [ ${BUILDTIME_DEPENDENCIES} -ne ${TOTAL_BUILDTIME_DEPENDENCIES} ]; then + echo "Install ALL of the missing ${BITSIZE} Buildtime Dependencies before preceding!" + exit 255 +fi +echo "Finished." + +# define the remaining variables +PACKAGE=svrcore-devel +VERSION=4.0.1 +RELEASE=3 +SVRCORE_TAG=SVRCORE_4_0_1_RTM +SVRCORE_CORECONF_TAG=$SVRCORE_TAG +PRJ=${PACKAGE}-${VERSION} +RPM_HOME=`pwd` +SPEC_FILENAME=${PACKAGE}.spec + +# define subroutines for this script +usage() { + echo + echo "Usage: $0" + echo +} + +mkdirs() { + for d in "$@" ; do + if [ -d $d ]; then + mv $d $d.deleted + rm -rf $d.deleted & + fi + mkdir -p $d + done +} + +# check the number of arguments supplied to this script +if [ $# -ne 0 ] ; then + usage + exit 255 +fi + +# remove any old RPM directories +echo "Removing any old RPM directories . . ." +if [ -d ${RPM_HOME}/BUILD ]; then + rm -rf ${RPM_HOME}/BUILD +fi +if [ -d ${RPM_HOME}/SOURCES ]; then + rm -rf ${RPM_HOME}/SOURCES +fi +if [ -d ${RPM_HOME}/SPECS ]; then + rm -rf ${RPM_HOME}/SPECS +fi +echo "Finished." + +echo "Changing current working directory to ${RPM_HOME}." +cd ${RPM_HOME} + +# create new RPM directories +echo "Creating new RPM directories . . ." +mkdirs BUILD +if [ ! -d ${RPM_HOME}/RPMS ]; then + mkdirs ${RPM_HOME}/RPMS +fi +if [ ! -d ${RPM_HOME}/SGTARS ]; then + mkdirs ${RPM_HOME}/SGTARS +fi +mkdirs SOURCES SPECS +if [ ! -d ${RPM_HOME}/SRPMS ]; then + mkdirs ${RPM_HOME}/SRPMS +fi +echo "Finished." + +# check out SVRCORE CORECONF code +echo "Checking out SVRCORE CORECONF source code . . ." +cvs -z3 -Q export -r ${SVRCORE_CORECONF_TAG} -d ${PRJ} -N mozilla/security/coreconf +echo "Finished." + +# check out SVRCORE code +echo "Checking out SVRCORE source code . . ." +cvs -z3 -Q export -r ${SVRCORE_TAG} -d ${PRJ} -N mozilla/security/svrcore +echo "Finished." + +# create a tarball from the checked out code +echo "Creating tarball of SVRCORE source code . . ." +tar cf - ${PRJ} | gzip > SOURCES/${PRJ}.tar.gz +echo "Finished." + +# remove the checked out code +echo "Removing checked out SVRCORE source code . . ." +rm -rf ${PRJ} +echo "Finished." + +# copy spec file +cp ${SPEC_FILENAME} SPECS/${SPEC_FILENAME} + +# copy the SVRCORE source file template +cp ${SVRCORE_TEMPLATE} SOURCES/${SVRCORE_TEMPLATE} + +# build the ${BITSIZE} RPM and Source RPM +echo "Executing ${BITSIZE} rpmbuild of ${SPEC_FILENAME} file . . . " +if [ ! -f SRPMS/${PACKAGE}-${VERSION}-${RELEASE}.src.rpm ]; then + rpmbuild --define="_topdir ${RPM_HOME}" --target ${PLATFORM} -ba --clean --rmsource --rmspec SPECS/${SPEC_FILENAME} +else + rpmbuild --define="_topdir ${RPM_HOME}" --target ${PLATFORM} -bb --clean --rmsource --rmspec SPECS/${SPEC_FILENAME} +fi +echo "Finished doing ${BITSIZE} rpmbuild of ${SPEC_FILENAME} file." + +echo "Removing BUILD directory . . ." +if [ -d ${RPM_HOME}/BUILD ]; then + rm -rf ${RPM_HOME}/BUILD +fi +echo "Finished." + +echo "Removing SOURCES directory . . ." +if [ -d ${RPM_HOME}/SOURCES ]; then + rm -rf ${RPM_HOME}/SOURCES +fi +echo "Finished." + +echo "Removing SPECS directory . . ." +if [ -d ${RPM_HOME}/SPECS ]; then + rm -rf ${RPM_HOME}/SPECS +fi +echo "Finished." + diff --git a/svrcore.spec b/svrcore.spec index eefa5220c..a72138431 100644 --- a/svrcore.spec +++ b/svrcore.spec @@ -4,14 +4,15 @@ Summary: Svrcore - development files for secure PIN handling using NSS crypto Name: svrcore-devel Version: 4.0.1 -Release: 2 +Release: 3 License: MPL/GPL/LGPL URL: http://www.mozilla.org/projects/security/pki/ Group: Development/Libraries -Requires: nspr-devel >= %{nspr_version}, nss-devel >= %{nss_version} +Requires: nspr-devel >= %{nspr_version} +Requires: nss-devel >= %{nss_version} BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) -BuildRequires: nspr-devel >= %{nspr_version}, nss-devel >= %{nss_version} -BuildRequires: pkgconfig +BuildRequires: nspr-devel >= %{nspr_version} +BuildRequires: nss-devel >= %{nss_version} BuildRequires: gawk Provides: svrcore-devel @@ -38,21 +39,16 @@ export BUILD_OPT XCFLAGS=$RPM_OPT_FLAGS export XCFLAGS -#export NSPR_INCLUDE_DIR=`nspr-config --includedir` -#export NSPR_LIB_DIR=`nspr-config --libdir` - PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 export PKG_CONFIG_ALLOW_SYSTEM_LIBS export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS -NSPR_INCLUDE_DIR=`/usr/bin/pkg-config --cflags-only-I nspr | sed 's/-I//'` - +NSPR_INCLUDE_DIR=`/usr/bin/pkg-config --variable=includedir nspr` export NSPR_INCLUDE_DIR -NSS_INCLUDE_DIR=`/usr/bin/pkg-config --cflags-only-I nss | sed 's/-I//'` - +NSS_INCLUDE_DIR=`/usr/bin/pkg-config --variable=includedir nss` export NSS_INCLUDE_DIR %ifarch x86_64 ppc64 ia64 s390x @@ -71,11 +67,11 @@ make EXPORTS="" RELEASE="" REQUIRES="" MODULE="" IMPORTS="" OBJDIR=. INSTALL=tru %{__cat} svrcore.pc.in | sed -e "s,%%libdir%%,%{_libdir},g" \ -e "s,%%prefix%%,%{_prefix},g" \ -e "s,%%exec_prefix%%,%{_prefix},g" \ - -e "s,%%includedir%%,%{_includedir}/nss3,g" \ + -e "s,%%includedir%%,%{_includedir},g" \ -e "s,%%NSPR_VERSION%%,%{nspr_version},g" \ -e "s,%%NSS_VERSION%%,%{nss_version},g" \ -e "s,%%SVRCORE_VERSION%%,%{version},g" > \ - $RPM_BUILD_ROOT/%{_libdir}/pkgconfig/svrcore.pc + $RPM_BUILD_ROOT/%{_libdir}/pkgconfig/%{name}.pc %install @@ -103,11 +99,14 @@ done %files %defattr(0644,root,root) -%{_libdir}/pkgconfig/svrcore.pc +%{_libdir}/pkgconfig/%{name}.pc %{_libdir}/libsvrcore.a %{_includedir}/svrcore.h %changelog +* Tue Apr 18 2006 Rich Megginson <[email protected]> - 4.0.1-3 +- Use pkg-config --variable=includedir to get include dirs + * Wed Feb 1 2006 Rich <[email protected]> - 4.0.1-2 - Requires nss version was wrong
0
14cb1d07ee1864de8ca54083ef6901d5b4627758
389ds/389-ds-base
Ticket 366 - Change DS to purge ticket from krb cache in case of authentication error Bug Description: Under certain circumstances, a replica can be removed, and readded, but the master replica still holds its old kerberos credentials in a cache(ccache). Until the mater replica is restarted, replication will not resume. Fix Description: If a sasl bind fails, ands it a GSSAPI, and the errror is 49, clear out the ccache. I also noticed that when this situation arises we report errors when trying to update the referrals in the repl agreement to this replica. The error is 20(type or value exists), and it will log at least one of these messages per update. The error should not be written to the error log, as it's not a problem that needs reporting. https://fedorahosted.org/389/ticket/366 reviewed by: richm(Thanks!)
commit 14cb1d07ee1864de8ca54083ef6901d5b4627758 Author: Mark Reynolds <[email protected]> Date: Wed Jun 27 10:35:08 2012 -0400 Ticket 366 - Change DS to purge ticket from krb cache in case of authentication error Bug Description: Under certain circumstances, a replica can be removed, and readded, but the master replica still holds its old kerberos credentials in a cache(ccache). Until the mater replica is restarted, replication will not resume. Fix Description: If a sasl bind fails, ands it a GSSAPI, and the errror is 49, clear out the ccache. I also noticed that when this situation arises we report errors when trying to update the referrals in the repl agreement to this replica. The error is 20(type or value exists), and it will log at least one of these messages per update. The error should not be written to the error log, as it's not a problem that needs reporting. https://fedorahosted.org/389/ticket/366 reviewed by: richm(Thanks!) diff --git a/ldap/servers/plugins/replication/replutil.c b/ldap/servers/plugins/replication/replutil.c index b09bf537e..5e8019c7e 100644 --- a/ldap/servers/plugins/replication/replutil.c +++ b/ldap/servers/plugins/replication/replutil.c @@ -788,7 +788,7 @@ repl_set_mtn_state_and_referrals( } } - if (rc != LDAP_SUCCESS) { + if (rc != LDAP_SUCCESS && rc != LDAP_TYPE_OR_VALUE_EXISTS) { slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "repl_set_mtn_referrals: could " "not set referrals for replica %s: %d\n", slapi_sdn_get_dn(repl_root_sdn), rc); diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index 399081594..fd4e93fc3 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -126,6 +126,10 @@ static char **mozldap_ldap_explode( const char *dn, const int notypes, const int static char **mozldap_ldap_explode_dn( const char *dn, const int notypes ); static char **mozldap_ldap_explode_rdn( const char *rdn, const int notypes ); +#ifdef HAVE_KRB5 +static void clear_krb5_ccache(); +#endif + #ifdef MEMPOOL_EXPERIMENTAL void _free_wrapper(void *ptr) { @@ -1159,6 +1163,12 @@ slapi_ldap_bind( bindid ? bindid : "(anon)", mech, /* mech cannot be SIMPLE here */ rc, ldap_err2string(rc)); +#ifdef HAVE_KRB5 + if(mech && !strcmp(mech, "GSSAPI") && rc == 49){ + /* only on err 49 should we clear out the credential cache */ + clear_krb5_ccache(); + } +#endif } } @@ -2062,6 +2072,43 @@ cleanup: return; } +static void +clear_krb5_ccache() +{ + krb5_context ctx = NULL; + krb5_ccache cc = NULL; + int rc = 0; + + PR_Lock(krb5_lock); + + /* initialize the kerberos context */ + if ((rc = krb5_init_context(&ctx))) { + slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not initialize kerberos context: %d (%s)\n", + rc, error_message(rc)); + goto done; + } + /* get the default ccache */ + if ((rc = krb5_cc_default(ctx, &cc))) { + slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not get default kerberos ccache: %d (%s)\n", + rc, error_message(rc)); + goto done; + } + /* destroy the ccache */ + if((rc = krb5_cc_destroy(ctx, cc))){ + slapi_log_error(SLAPI_LOG_FATAL, "clear_krb5_ccache", "Could not destroy kerberos ccache: %d (%s)\n", + rc, error_message(rc)); + } else { + slapi_log_error(SLAPI_LOG_TRACE,"clear_krb5_ccache", "Successfully cleared kerberos ccache\n"); + } + +done: + if(ctx){ + krb5_free_context(ctx); + } + + PR_Unlock(krb5_lock); +} + #endif /* HAVE_KRB5 */ #define LDAP_DN 1
0
d8cdb35018d63757de165c9d47f4734780f41c1b
389ds/389-ds-base
Ticket #422 - 389-ds-base - Can't call method "getText" Bug description: If a hostname which has no corresponding IP address associated is given to the setup-ds-admin.pl or setup-ds.pl (e.g., bogus.bogus.bogus.com), then DSUtil.pm complains with "Can't call method "getText" on an undefined value". Fix description: Thanks to Rich for his comments. Following his suggestions, this patch prepares 2 different return types in checkHostname depending upon the existence of the resource object. If the resource is given, the subroutine returns the error message. Otherwise, it returns the array of error message. https://fedorahosted.org/389/ticket/422
commit d8cdb35018d63757de165c9d47f4734780f41c1b Author: Noriko Hosoi <[email protected]> Date: Fri Dec 21 10:31:24 2012 -0800 Ticket #422 - 389-ds-base - Can't call method "getText" Bug description: If a hostname which has no corresponding IP address associated is given to the setup-ds-admin.pl or setup-ds.pl (e.g., bogus.bogus.bogus.com), then DSUtil.pm complains with "Can't call method "getText" on an undefined value". Fix description: Thanks to Rich for his comments. Following his suggestions, this patch prepares 2 different return types in checkHostname depending upon the existence of the resource object. If the resource is given, the subroutine returns the error message. Otherwise, it returns the array of error message. https://fedorahosted.org/389/ticket/422 diff --git a/ldap/admin/src/scripts/DSCreate.pm.in b/ldap/admin/src/scripts/DSCreate.pm.in index 1d5e71ace..92035a23d 100644 --- a/ldap/admin/src/scripts/DSCreate.pm.in +++ b/ldap/admin/src/scripts/DSCreate.pm.in @@ -150,9 +150,9 @@ sub sanityCheckParams { debug(0, "WARNING: The root password is less than 8 characters long. You should choose a longer one.\n"); } - my $str = checkHostname($inf->{General}->{FullMachineName}); - if ($str) { - debug(0, $str); + if (@errs = checkHostname($inf->{General}->{FullMachineName}, 0)) { + debug(1, @errs); + return @errs; } return (); diff --git a/ldap/admin/src/scripts/DSUtil.pm.in b/ldap/admin/src/scripts/DSUtil.pm.in index cc64a2d57..0f72571f6 100644 --- a/ldap/admin/src/scripts/DSUtil.pm.in +++ b/ldap/admin/src/scripts/DSUtil.pm.in @@ -207,7 +207,8 @@ sub isValidGroup { # arguments # - hostname - the hostname to look for # - res - the Resource object to use to construct messages -# returns - the error message string, or "" upon success +# returns - the error message string, or "" upon success if $res exists +# - the error message array, or () upon success otherwise sub checkHostname { my $hn = shift; my $res = shift; @@ -217,7 +218,7 @@ sub checkHostname { if ($res) { return $res->getText('warning_hostname_not_fully_qualified', $hn); } else { - return "Warning: hostname $hn is not a fully qualified host and domain name\n"; + return ('warning_hostname_not_fully_qualified', $hn); } } @@ -229,7 +230,11 @@ sub checkHostname { my %hints = (socktype => SOCK_STREAM); my ($err, @aires) = getaddrinfo($hn, "ldap", \%hints); if ($err) { - return $res->getText('warning_no_such_hostname', $hn); + if ($res) { + return $res->getText('warning_no_such_hostname', $hn); + } else { + return ('warning_no_such_hostname', $hn); + } } while (my $ai = shift @aires) { debug(1, "found for hostname $hn\n"); @@ -256,7 +261,11 @@ sub checkHostname { debug(1, "Socket6\n"); my @aires = getaddrinfo($hn, "ldap", AF_UNSPEC, SOCK_STREAM); if (scalar(@aires) < 5) { - return $res->getText('warning_no_such_hostname', $hn); + if ($res) { + return $res->getText('warning_no_such_hostname', $hn); + } else { + return ('warning_no_such_hostname', $hn); + } } my $ailen = scalar(@aires); while ($ailen >= 5) { @@ -293,7 +302,7 @@ sub checkHostname { if ($res) { return $res->getText('warning_no_such_hostname', $hn); } else { - return "Warning: could not resolve hostname $hn\n"; + return ('warning_no_such_hostname', $hn); } } debug(1, "found for hostname $hn: name=$name\n"); @@ -313,24 +322,29 @@ sub checkHostname { } if (!$found) { - my $retstr = ""; if ($res) { + my $retstr = ""; $retstr = $res->getText('warning_reverse_resolve', $hn, $hn); - } else { - $retstr = "Warning: Hostname $hn is valid, but none of the IP addresses\nresolve back to $hn\n"; - } - for my $ii (@hostip) { - if ($res) { + for my $ii (@hostip) { $retstr .= $res->getText('warning_reverse_resolve_sub', $ii->[1], $ii->[0]); - } else { - $retstr .= "\taddress $ii->[1] resolves to host $ii->[0]\n"; } + return $retstr; + } else { + my @reterrs = (); + push @reterrs, [ 'warning_reverse_resolve', $hn, $hn ]; + for my $ii (@hostip) { + push @reterrs, [ 'warning_reverse_resolve_sub', $ii->[1], $ii->[0] ]; + } + return @reterrs; } - return $retstr; } debug(1, "hostname $hn resolves correctly\n"); - return ''; + if ($res) { + return ''; + } else { + return (); + } } # delete the subtree starting from the passed entry
0
c917b93a2f625c2a58d35a88a5a547efcf7fec9b
389ds/389-ds-base
Ticket 49443 - scope one searches in 1.3.7 give incorrect results Bug: if a onelevel search is done for an unidexed attribute, the filter test is skipped and all children of the search base are returned Fix: enforce filter test if allids Reviewed by: Mark, thanks
commit c917b93a2f625c2a58d35a88a5a547efcf7fec9b Author: Ludwig Krispenz <[email protected]> Date: Thu Nov 9 10:20:44 2017 +0100 Ticket 49443 - scope one searches in 1.3.7 give incorrect results Bug: if a onelevel search is done for an unidexed attribute, the filter test is skipped and all children of the search base are returned Fix: enforce filter test if allids Reviewed by: Mark, thanks diff --git a/ldap/servers/slapd/back-ldbm/idl_set.c b/ldap/servers/slapd/back-ldbm/idl_set.c index ba39ff03f..b68e7ab76 100644 --- a/ldap/servers/slapd/back-ldbm/idl_set.c +++ b/ldap/servers/slapd/back-ldbm/idl_set.c @@ -349,6 +349,11 @@ idl_set_intersect(IDListSet *idl_set, backend *be) { IDList *result_list = NULL; + if (idl_set->allids) { + /* if any component was allids we have to apply the filtertest */ + slapi_be_set_flag(be, SLAPI_BE_FLAG_DONT_BYPASS_FILTERTEST); + } + if (idl_set->allids != 0 && idl_set->count == 0) { /* * We only have allids, so must be allids.
0
f5dc7260fba62a04bfe46eb48081db7c3fe2322c
389ds/389-ds-base
bump version to 1.2.7.3
commit f5dc7260fba62a04bfe46eb48081db7c3fe2322c Author: Rich Megginson <[email protected]> Date: Wed Dec 8 11:45:17 2010 -0700 bump version to 1.2.7.3 diff --git a/VERSION.sh b/VERSION.sh index 996a9d031..fa4dc3885 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -10,7 +10,7 @@ vendor="389 Project" # PACKAGE_VERSION is constructed from these VERSION_MAJOR=1 VERSION_MINOR=2 -VERSION_MAINT=7.2 +VERSION_MAINT=7.3 # if this is a PRERELEASE, set VERSION_PREREL # otherwise, comment it out # be sure to include the dot prefix in the prerel
0
1808f317d5ef240fd0ac3947fcb90a895e46b436
389ds/389-ds-base
Ticket 50308 - Revise memory leak fix Description; Turns out the previous commit did not address the changelog leak, and it introduced a compiler warning. This part of the fix is being reverted. https://pagure.io/389-ds-base/issue/50308
commit 1808f317d5ef240fd0ac3947fcb90a895e46b436 Author: Mark Reynolds <[email protected]> Date: Fri Mar 29 14:59:05 2019 -0400 Ticket 50308 - Revise memory leak fix Description; Turns out the previous commit did not address the changelog leak, and it introduced a compiler warning. This part of the fix is being reverted. https://pagure.io/389-ds-base/issue/50308 diff --git a/ldap/servers/plugins/replication/cl5_clcache.c b/ldap/servers/plugins/replication/cl5_clcache.c index 6c1882952..6b591fb8d 100644 --- a/ldap/servers/plugins/replication/cl5_clcache.c +++ b/ldap/servers/plugins/replication/cl5_clcache.c @@ -547,6 +547,7 @@ clcache_refresh_consumer_maxcsns(CLC_Buffer *buf) int i; for (i = 0; i < buf->buf_num_cscbs; i++) { + csn_free(&buf->buf_cscbs[i]->consumer_maxcsn); ruv_get_largest_csn_for_replica( buf->buf_consumer_ruv, buf->buf_cscbs[i]->rid, @@ -589,7 +590,6 @@ clcache_refresh_local_maxcsn(const ruv_enum_data *rid_data, void *data) /* this is the first time we have a local change for the RID * we need to check what the consumer knows about it. */ - csn_free(&buf->buf_cscbs[i]->consumer_maxcsn); ruv_get_largest_csn_for_replica( buf->buf_consumer_ruv, buf->buf_cscbs[i]->rid, @@ -833,7 +833,6 @@ clcache_skip_change(CLC_Buffer *buf) /* Send CSNs that are covered by the local RUV snapshot */ if (csn_compare(buf->buf_current_csn, cscb->local_maxcsn) <= 0) { skip = 0; - csn_free(&cscb->consumer_maxcsn); csn_dup_or_init_by_csn(&cscb->consumer_maxcsn, buf->buf_current_csn); break; } @@ -848,8 +847,7 @@ clcache_skip_change(CLC_Buffer *buf) { csn_init_by_csn(cscb->local_maxcsn, buf->buf_current_csn); if (cscb->consumer_maxcsn) { - csn_free(&cscb->consumer_maxcsn); - csn_dup_or_init_by_csn(cscb->consumer_maxcsn, buf->buf_current_csn); + csn_init_by_csn(cscb->consumer_maxcsn, buf->buf_current_csn); } skip = 0; break;
0
da9030b8c3ceb057ddb92d04ceafce3976418438
389ds/389-ds-base
16578 - Fixed off by one error in month in logconv.pl
commit da9030b8c3ceb057ddb92d04ceafce3976418438 Author: Nathan Kinder <[email protected]> Date: Tue Apr 18 18:57:44 2006 +0000 16578 - Fixed off by one error in month in logconv.pl diff --git a/ldap/admin/src/logconv.pl b/ldap/admin/src/logconv.pl index 945c81259..9019e9a14 100755 --- a/ldap/admin/src/logconv.pl +++ b/ldap/admin/src/logconv.pl @@ -275,18 +275,18 @@ $connmsg{"P2"} = "Poll"; $connmsg{"U1"} = "Cleanly Closed Connections"; %monthname = ( - "Jan" => 1, - "Feb" => 2, - "Mar" => 3, - "Apr" => 4, - "May" => 5, - "Jun" => 6, - "Jul" => 7, - "Aug" => 8, - "Sep" => 9, - "Oct" => 10, - "Nov" => 11, - "Dec" => 12, + "Jan" => 0, + "Feb" => 1, + "Mar" => 2, + "Apr" => 3, + "May" => 4, + "Jun" => 5, + "Jul" => 6, + "Aug" => 7, + "Sep" => 8, + "Oct" => 9, + "Nov" => 10, + "Dec" => 11, );
0
20d7abbbff383c5e3aaae8418d5d3af8f4c218a1
389ds/389-ds-base
Ticket 49052 - Environment quoting on fedora causes ds to fail to start. Bug Description: Systemd made a silent breaking change to the way they process environment values in .service files. This crippeled ASAN variants of DS. Fix Description: Change the quoting style. https://fedorahosted.org/389/ticket/49052 Author: wibrown Review by: vashirov
commit 20d7abbbff383c5e3aaae8418d5d3af8f4c218a1 Author: William Brown <[email protected]> Date: Mon Dec 12 14:07:04 2016 +1000 Ticket 49052 - Environment quoting on fedora causes ds to fail to start. Bug Description: Systemd made a silent breaking change to the way they process environment values in .service files. This crippeled ASAN variants of DS. Fix Description: Change the quoting style. https://fedorahosted.org/389/ticket/49052 Author: wibrown Review by: vashirov diff --git a/wrappers/systemd.template.asan.service.in b/wrappers/systemd.template.asan.service.in index 5de91de85..cfde3b5cc 100644 --- a/wrappers/systemd.template.asan.service.in +++ b/wrappers/systemd.template.asan.service.in @@ -23,7 +23,7 @@ EnvironmentFile=@initconfigdir@/@package_name@ EnvironmentFile=@initconfigdir@/@package_name@-%i PIDFile=@localstatedir@/run/@package_name@/slapd-%i.pid # We can't symbolize here, as llvm symbolize crashes when it goes near systemd. -Environment='ASAN_OPTIONS="detect_leaks=1 symbolize=0 log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.asan detect_deadlocks=1"' +Environment=ASAN_OPTIONS=log_path=@localstatedir@/run/@package_name@/ns-slapd-%i.asan LimitCORE=infinity ExecStartPre=@sbindir@/ds_systemd_ask_password_acl @instconfigdir@/slapd-%i/dse.ldif ExecStart=@sbindir@/ns-slapd -D @instconfigdir@/slapd-%i -i @localstatedir@/run/@package_name@/slapd-%i.pid
0
b1d67c11d98ff65116c74622ca72280f648def97
389ds/389-ds-base
Issue 50499 - Fix npm audit issues Description: Updated npm handlebars package to 4.5.2 relates: https://pagure.io/389-ds-base/issue/50499
commit b1d67c11d98ff65116c74622ca72280f648def97 Author: Mark Reynolds <[email protected]> Date: Fri Nov 15 11:04:14 2019 -0500 Issue 50499 - Fix npm audit issues Description: Updated npm handlebars package to 4.5.2 relates: https://pagure.io/389-ds-base/issue/50499 diff --git a/src/cockpit/389-console/package-lock.json b/src/cockpit/389-console/package-lock.json index 7207e92a0..f61e48985 100644 --- a/src/cockpit/389-console/package-lock.json +++ b/src/cockpit/389-console/package-lock.json @@ -6053,9 +6053,9 @@ "integrity": "sha512-zGEOVKFM5sVPPrYs7J5/hYEw2Pof8KCyOwyhG8sAF26mCAeUFAcYPu1mwB7hhpIP29zOIBaDqwuHdLp0jvZXjw==" }, "handlebars": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.5.1.tgz", - "integrity": "sha512-C29UoFzHe9yM61lOsIlCE5/mQVGrnIOrOq7maQl76L7tYPCgC1og0Ajt6uWnX4ZTxBPnjw+CUvawphwCfJgUnA==", + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.5.2.tgz", + "integrity": "sha512-29Zxv/cynYB7mkT1rVWQnV7mGX6v7H/miQ6dbEpYTKq5eJBN7PsRB+ViYJlcT6JINTSu4dVB9kOqEun78h6Exg==", "requires": { "neo-async": "^2.6.0", "optimist": "^0.6.1", @@ -6075,9 +6075,9 @@ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" }, "uglify-js": { - "version": "3.6.7", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.6.7.tgz", - "integrity": "sha512-4sXQDzmdnoXiO+xvmTzQsfIiwrjUCSA95rSP4SEd8tDb51W2TiDOlL76Hl+Kw0Ie42PSItCW8/t6pBNCF2R48A==", + "version": "3.6.9", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.6.9.tgz", + "integrity": "sha512-pcnnhaoG6RtrvHJ1dFncAe8Od6Nuy30oaJ82ts6//sGSXOP5UjBMEthiProjXmMNHOfd93sqlkztifFMcb+4yw==", "optional": true, "requires": { "commander": "~2.20.3", diff --git a/src/cockpit/389-console/package.json b/src/cockpit/389-console/package.json index ffa429d83..fb2449675 100644 --- a/src/cockpit/389-console/package.json +++ b/src/cockpit/389-console/package.json @@ -52,7 +52,7 @@ "@patternfly/react-core": "^3.58.1", "bootstrap": "^4.3.1", "file-loader": "^4.1.0", - "handlebars": "^4.4.5", + "handlebars": "^4.5.2", "node-sass": "4.12.0", "patternfly": "^3.59.3", "patternfly-react": "^2.34.3",
0
5878a3113c0a28ff8fc3a23452afd8895ffed06c
389ds/389-ds-base
Issue: 50686 - Port fractional replication test cases from TET to python3 part 1 Bug Description: Port fractional replication test cases from TET to python3 part 1 Relates: https://pagure.io/389-ds-base/issue/50686 Author: aborah Reviewed by: Viktor Ashirov
commit 5878a3113c0a28ff8fc3a23452afd8895ffed06c Author: Anuj Borah <[email protected]> Date: Fri Jan 17 12:18:30 2020 +0530 Issue: 50686 - Port fractional replication test cases from TET to python3 part 1 Bug Description: Port fractional replication test cases from TET to python3 part 1 Relates: https://pagure.io/389-ds-base/issue/50686 Author: aborah Reviewed by: Viktor Ashirov diff --git a/dirsrvtests/tests/suites/fractional/fractional_test.py b/dirsrvtests/tests/suites/fractional/fractional_test.py new file mode 100644 index 000000000..32dee16fe --- /dev/null +++ b/dirsrvtests/tests/suites/fractional/fractional_test.py @@ -0,0 +1,267 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2020 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +""" +This test script will test fractional replication. +""" + +import os +import pytest +from lib389.topologies import topology_m2c2 +from lib389._constants import DEFAULT_SUFFIX +from lib389.idm.user import UserAccounts, UserAccount +from lib389.replica import ReplicationManager +from lib389.agreement import Agreements +import ldap + +pytestmark = pytest.mark.tier1 + +MASTER1 = MASTER2 = CONSUMER1 = CONSUMER2 = None + + +def _create_users(instance, cn_cn, sn_sn, givenname, ou_ou, l_l, uid, mail, + telephonenumber, facsimiletelephonenumber, roomnumber): + """ + Will create sample user. + """ + user = instance.create(properties={ + 'cn': cn_cn, + 'sn': sn_sn, + 'givenname': givenname, + 'ou': ou_ou, + 'l': l_l, + 'uid': uid, + 'mail': mail, + 'telephonenumber': telephonenumber, + 'facsimiletelephonenumber': facsimiletelephonenumber, + 'roomnumber': roomnumber, + 'uidNumber': '111', + 'gidNumber': '111', + 'homeDirectory': f'/home/{uid}', + + }) + return user + + +def check_all_replicated(): + """ + Will check replication status + """ + for master in [MASTER2, CONSUMER1, CONSUMER2]: + ReplicationManager(DEFAULT_SUFFIX).wait_for_replication(MASTER1, master, timeout=100) + + [email protected](scope="module") +def _create_entries(topology_m2c2): + """ + A fixture that will create first test user and create fractional Agreement + """ + # Defining as global , as same value will be used everywhere with same name. + global MASTER1, MASTER2, CONSUMER1, CONSUMER2 + MASTER1 = topology_m2c2.ms['master1'] + MASTER2 = topology_m2c2.ms['master2'] + CONSUMER1 = topology_m2c2.cs['consumer1'] + CONSUMER2 = topology_m2c2.cs['consumer2'] + users = UserAccounts(MASTER1, DEFAULT_SUFFIX) + _create_users(users, 'Sam Carter', 'Carter', 'Sam', ['Accounting', 'People'], + 'Sunnyvale', 'scarter', '[email protected]', '+1 408 555 4798', + '+1 408 555 9751', '4612') + for ins, num in [(MASTER1, 1), (MASTER2, 2), (MASTER1, 2), (MASTER2, 1)]: + Agreements(ins).list()[num].replace( + 'nsDS5ReplicatedAttributeList', + '(objectclass=*) $ EXCLUDE audio businessCategory carLicense departmentNumber ' + 'destinationIndicator displayName employeeNumber employeeType facsimileTelephoneNumber ' + 'roomNumber telephoneNumber memberOf manager accountUnlockTime ' + 'passwordRetryCount retryCountResetTime') + Agreements(ins).list()[num].replace( + 'nsDS5ReplicatedAttributeListTotal', + '(objectclass=*) $ EXCLUDE audio businessCategory carLicense departmentNumber ' + 'destinationIndicator displayName employeeNumber employeeType facsimileTelephoneNumber ' + 'roomNumber telephoneNumber accountUnlockTime passwordRetryCount retryCountResetTime') + Agreements(ins).list()[num].begin_reinit() + Agreements(ins).list()[num].wait_reinit() + + +def test_fractional_agreements(_create_entries): + """The attributes should be present on the two suppliers with traditional replication + agreements, but not with fractional agreements. + + :id: f22395e0-38ea-11ea-abe0-8c16451d917b + :setup: Master and Consumer + :steps: + 1. Add test entry + 2. Search for an entry with disallowed attributes on every server. + 3. The attributes should be present on the two suppliers with traditional replication + agreements + 4. Should be missing on both consumers with fractional agreements. + :expected results: + 1. Success + 2. Success + 3. Success + 4. Success + """ + check_all_replicated() + # Search for an entry with disallowed attributes on every server. + for attr in ['telephonenumber', 'facsimiletelephonenumber', 'roomnumber']: + assert UserAccount(MASTER1, f'uid=scarter,ou=People,{DEFAULT_SUFFIX}').get_attr_val(attr) + assert UserAccount(MASTER2, f'uid=scarter,ou=People,{DEFAULT_SUFFIX}').get_attr_val(attr) + # The attributes should be present on the two suppliers with + # traditional replication agreements + for attr in ['telephonenumber', 'facsimiletelephonenumber', 'roomnumber']: + assert not UserAccount(CONSUMER1, + f'uid=scarter,ou=People,{DEFAULT_SUFFIX}').get_attr_val(attr) + assert not UserAccount(CONSUMER2, + f'uid=scarter,ou=People,{DEFAULT_SUFFIX}').get_attr_val(attr) + + +def test_read_only_consumer(_create_entries): + """Attempt to modify an entry on read-only consumer. + + :id: f97f0fea-38ea-11ea-a617-8c16451d917b + :setup: Master and Consumer + :steps: + 1. Add test entry + 2. First attempt to modify an attribute that should be visible (mail) + 3. Then attempt to modify one that should not be visible (roomnumber) + :expected results: + 1. Success + 2. Fail(ldap.INSUFFICIENT_ACCESS) + 3. Fail(ldap.INSUFFICIENT_ACCESS) + """ + # Add test entry + user_consumer1 = UserAccount(CONSUMER1, f'uid=scarter,ou=People,{DEFAULT_SUFFIX}') + user_consumer2 = UserAccount(CONSUMER2, f'uid=scarter,ou=People,{DEFAULT_SUFFIX}') + # First attempt to modify an attribute that should be visible (mail) + for attr, value in [('mail', '[email protected]'), ('roomnumber', '123')]: + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_consumer1.replace(attr, value) + # Then attempt to modify one that should not be visible (room number) + for attr, value in [('mail', '[email protected]'), ('roomnumber', '123')]: + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_consumer2.replace(attr, value) + + +def test_read_write_supplier(_create_entries): + """Attempt to modify an entry on read-write supplier + + :id: ff50a8b6-38ea-11ea-870f-8c16451d917b + :setup: Master and Consumer + :steps: + 1. Add test entry + 2. First attempt to modify an attribute that should be visible (mail) + 3. Then attempt to modify one that should not be visible (roomnumber) + 4. The change to mail should appear on all servers; the change to + room number should only appear on the suppliers INST[0] and INST[1]. + :expected results: + 1. Success + 2. Success + 3. Success + 4. Success + """ + # Add test entry + user_master1 = UserAccount(MASTER1, f'uid=scarter,ou=People,{DEFAULT_SUFFIX}') + # First attempt to modify an attribute that should be visible (mail) + for attr, value in [('mail', '[email protected]'), ('roomnumber', '123')]: + user_master1.replace(attr, value) + check_all_replicated() + for ins, attr in [(MASTER2, 'mail'), + (MASTER2, 'roomnumber'), + (CONSUMER1, 'mail'), + (CONSUMER2, 'mail')]: + if attr == 'mail': + assert UserAccount(ins, + f'uid=scarter,' + f'ou=People,{DEFAULT_SUFFIX}').get_attr_val_utf8(attr) == \ + '[email protected]' + elif attr == 'roomnumber': + assert UserAccount(ins, + f'uid=scarter,' + f'ou=People,{DEFAULT_SUFFIX}').get_attr_val_utf8(attr) == '123' + # Attempt to modify one that should not be visible (room number) + for ins in [CONSUMER1, CONSUMER2]: + assert not UserAccount(ins, + f'uid=scarter,ou=People,{DEFAULT_SUFFIX}').get_attr_val('roomnumber') + + +def test_filtered_attributes(_create_entries): + """Filtered attributes are not replicated to CONSUMER1 or CONSUMER2. + + :id: 051b40ee-38eb-11ea-9126-8c16451d917b + :setup: Master and Consumer + :steps: + 1. Add a new entry to MASTER1. + 2. Confirm that it is replicated in entirety + to MASTER2, but that filtered attributes are not replicated to + CONSUMER1 or CONSUMER2. + 3. The entry should be present in all servers. Filtered attributes should not + be available from the consumers with fractional replication agreements. + :expected results: + 1. Success + 2. Success + 3. Success + """ + # Add a new entry to MASTER1. + users = UserAccounts(MASTER1, DEFAULT_SUFFIX) + _create_users(users, 'Anuj Borah', 'aborah', 'Anuj', 'People', 'ok', + 'aborah', '[email protected]', '+1121', '+121', '2121') + check_all_replicated() + for instance in [MASTER1, MASTER2, CONSUMER1, CONSUMER2]: + assert UserAccount(instance, + f'uid=aborah,' + f'ou=People,{DEFAULT_SUFFIX}').get_attr_val_utf8('mail') == \ + '[email protected]' + for instance in [MASTER1, MASTER2]: + assert UserAccount(instance, + f'uid=aborah,' + f'ou=People,{DEFAULT_SUFFIX}').get_attr_val_utf8('roomnumber') == '2121' + # The entry should be present in all servers. Filtered attributes should not + # be available from the consumers with fractional replication agreements. + for instance in [CONSUMER1, CONSUMER2]: + assert not UserAccount(instance, + f'uid=aborah,' + f'ou=People,{DEFAULT_SUFFIX}').get_attr_val_utf8('roomnumber') + + [email protected] +def test_fewer_changes_in_single_operation(_create_entries): + """For bug 154948, which cause the server to crash if there were + fewer changes (but more than one) in a single operation to fractionally + replicated attributes than the number of fractionally replicated attributes. + The primary test is that all servers are still alive. + + :id: 0d1d6218-38eb-11ea-8945-8c16451d917b + :setup: Master and Consumer + :steps: + 1. Add a new entry to MASTER1. + 2. Fewer changes (but more than one) in a single operation to fractionally + replicated attributes than the number of fractionally replicated attributes. + 3. All servers are still alive. + :expected results: + 1. Success + 2. Success + 3. Success + """ + users = UserAccounts(MASTER1, DEFAULT_SUFFIX) + user = _create_users(users, 'Anuj Borah1', 'aborah1', 'Anuj1', 'People', + 'ok1', 'aborah1', '[email protected]', '+11212', '+1212', '21231') + check_all_replicated() + # Fewer changes (but more than one) in a single operation to fractionally + # replicated attributes than the number of fractionally replicated attributes. + user.replace_many(('carLicense', '111-1111'), ('description', 'Hi')) + check_all_replicated() + user.replace_many(('mail', '[email protected]'), ('sn', 'Oak'), ('l', 'NewPlace')) + check_all_replicated() + # All servers are still alive. + for ints in [MASTER1, MASTER2, CONSUMER1, CONSUMER2]: + assert UserAccount(ints, user.dn).get_attr_val_utf8('mail') == '[email protected]' + assert UserAccount(ints, user.dn).get_attr_val_utf8('sn') == 'Oak' + + +if __name__ == '__main__': + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s -v %s" % CURRENT_FILE)
0
91fa21f6af7871d73bb9d5e738ec4e31b5298463
389ds/389-ds-base
Bug 755725 - 389 programs linked against openldap crash during shutdown https://bugzilla.redhat.com/show_bug.cgi?id=755725 Resolves: bug 755725 Bug Description: 389 programs linked against openldap crash during shutdown Reviewed by: nhosoi (Thanks!) Branch: master Fix Description: With recent versions of openldap, you cannot link with both ldap_r and ldap - when the shared object _fini is run, the _fini from the one will stomp on the _fini from the other, and the program will crash. The fix is to link with ldap_r only in a threaded program, and ldap otherwise. Platforms tested: Fedora 16, RHEL6 x86_64 Flag Day: no Doc impact: no
commit 91fa21f6af7871d73bb9d5e738ec4e31b5298463 Author: Rich Megginson <[email protected]> Date: Wed Dec 14 20:04:48 2011 -0700 Bug 755725 - 389 programs linked against openldap crash during shutdown https://bugzilla.redhat.com/show_bug.cgi?id=755725 Resolves: bug 755725 Bug Description: 389 programs linked against openldap crash during shutdown Reviewed by: nhosoi (Thanks!) Branch: master Fix Description: With recent versions of openldap, you cannot link with both ldap_r and ldap - when the shared object _fini is run, the _fini from the one will stomp on the _fini from the other, and the program will crash. The fix is to link with ldap_r only in a threaded program, and ldap otherwise. Platforms tested: Fedora 16, RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/Makefile.am b/Makefile.am index f4af8edc2..25ae2e543 100644 --- a/Makefile.am +++ b/Makefile.am @@ -45,11 +45,15 @@ endif NSPR_LINK = @nspr_lib@ -lplc4 -lplds4 -lnspr4 NSS_LINK = @nss_lib@ -lssl3 -lnss3 if OPENLDAP -LDAPSDK_LINK = @openldap_lib@ -lldap_r@ol_libver@ -lldap@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ +# with recent versions of openldap - if you link with both ldap_r and ldap, the +# shared lib _fini for one will stomp on the other, and the program will crash +LDAPSDK_LINK_NOTHR = @openldap_lib@ -lldap@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ +LDAPSDK_LINK = @openldap_lib@ -lldap_r@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ ldaplib = openldap ldaplib_defs = -DUSE_OPENLDAP else LDAPSDK_LINK = @ldapsdk_lib@ -lssldap60 -lprldap60 -lldap60 -lldif60 +LDAPSDK_LINK_NOTHR = $(LDAPSDK_LINK) ldaplib = mozldap ldaplib_defs = endif @@ -1229,7 +1233,7 @@ ldap_agent_bin_SOURCES = ldap/servers/snmp/main.c \ ldap/servers/slapd/agtmmap.c ldap_agent_bin_CPPFLAGS = $(AM_CPPFLAGS) @netsnmp_inc@ @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -ldap_agent_bin_LDADD = $(LDAPSDK_LINK) $(SASL_LINK) $(NSS_LINK) $(NSPR_LINK) $(NETSNMP_LINK) $(THREADLIB) +ldap_agent_bin_LDADD = $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) $(NSS_LINK) $(NSPR_LINK) $(NETSNMP_LINK) $(THREADLIB) if SOLARIS ldap_agent_bin_LDADD += -lrt endif @@ -1264,7 +1268,7 @@ ldclt_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) $(LIBNSL ldif_bin_SOURCES = ldap/servers/slapd/tools/ldif.c ldif_bin_CPPFLAGS = $(AM_CPPFLAGS) @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -ldif_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +ldif_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) #------------------------ # migratecred @@ -1280,7 +1284,7 @@ migratecred_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(L mmldif_bin_SOURCES = ldap/servers/slapd/tools/mmldif.c mmldif_bin_CPPFLAGS = $(AM_CPPFLAGS) @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -mmldif_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +mmldif_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) #------------------------ # ns-slapd diff --git a/Makefile.in b/Makefile.in index bc6a4d589..00b47ce91 100644 --- a/Makefile.in +++ b/Makefile.in @@ -825,7 +825,8 @@ am_ldap_agent_bin_OBJECTS = \ ldap/servers/snmp/ldap_agent_bin-ldap-agent.$(OBJEXT) \ ldap/servers/slapd/ldap_agent_bin-agtmmap.$(OBJEXT) ldap_agent_bin_OBJECTS = $(am_ldap_agent_bin_OBJECTS) -ldap_agent_bin_DEPENDENCIES = $(am__DEPENDENCIES_1) \ +@OPENLDAP_FALSE@am__DEPENDENCIES_3 = $(am__DEPENDENCIES_1) +ldap_agent_bin_DEPENDENCIES = $(am__DEPENDENCIES_3) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) @@ -866,7 +867,7 @@ am_ldif_bin_OBJECTS = \ ldap/servers/slapd/tools/ldif_bin-ldif.$(OBJEXT) ldif_bin_OBJECTS = $(am_ldif_bin_OBJECTS) ldif_bin_DEPENDENCIES = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ - $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) + $(am__DEPENDENCIES_3) $(am__DEPENDENCIES_1) am_makstrdb_OBJECTS = lib/libsi18n/makstrdb-makstrdb.$(OBJEXT) makstrdb_OBJECTS = $(am_makstrdb_OBJECTS) makstrdb_LDADD = $(LDADD) @@ -880,7 +881,7 @@ am_mmldif_bin_OBJECTS = \ mmldif_bin_OBJECTS = $(am_mmldif_bin_OBJECTS) mmldif_bin_DEPENDENCIES = libslapd.la $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \ - $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) + $(am__DEPENDENCIES_3) $(am__DEPENDENCIES_1) am__ns_slapd_SOURCES_DIST = ldap/servers/slapd/abandon.c \ ldap/servers/slapd/auth.c ldap/servers/slapd/bind.c \ ldap/servers/slapd/compare.c ldap/servers/slapd/config.c \ @@ -1322,8 +1323,12 @@ PLUGIN_CPPFLAGS = $(AM_CPPFLAGS) @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_in #------------------------ NSPR_LINK = @nspr_lib@ -lplc4 -lplds4 -lnspr4 NSS_LINK = @nss_lib@ -lssl3 -lnss3 +@OPENLDAP_FALSE@LDAPSDK_LINK_NOTHR = $(LDAPSDK_LINK) +# with recent versions of openldap - if you link with both ldap_r and ldap, the +# shared lib _fini for one will stomp on the other, and the program will crash +@OPENLDAP_TRUE@LDAPSDK_LINK_NOTHR = @openldap_lib@ -lldap@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ @OPENLDAP_FALSE@LDAPSDK_LINK = @ldapsdk_lib@ -lssldap60 -lprldap60 -lldap60 -lldif60 -@OPENLDAP_TRUE@LDAPSDK_LINK = @openldap_lib@ -lldap_r@ol_libver@ -lldap@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ +@OPENLDAP_TRUE@LDAPSDK_LINK = @openldap_lib@ -lldap_r@ol_libver@ @ldap_lib_ldif@ -llber@ol_libver@ @OPENLDAP_FALSE@ldaplib = mozldap @OPENLDAP_TRUE@ldaplib = openldap @OPENLDAP_FALSE@ldaplib_defs = @@ -2368,7 +2373,7 @@ ldap_agent_bin_SOURCES = ldap/servers/snmp/main.c \ ldap/servers/slapd/agtmmap.c ldap_agent_bin_CPPFLAGS = $(AM_CPPFLAGS) @netsnmp_inc@ @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -ldap_agent_bin_LDADD = $(LDAPSDK_LINK) $(SASL_LINK) $(NSS_LINK) \ +ldap_agent_bin_LDADD = $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) $(NSS_LINK) \ $(NSPR_LINK) $(NETSNMP_LINK) $(THREADLIB) $(am__append_2) #------------------------ @@ -2394,7 +2399,7 @@ ldclt_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) $(LIBNSL #------------------------ ldif_bin_SOURCES = ldap/servers/slapd/tools/ldif.c ldif_bin_CPPFLAGS = $(AM_CPPFLAGS) @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -ldif_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +ldif_bin_LDADD = $(NSPR_LINK) $(NSS_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) #------------------------ # migratecred @@ -2408,7 +2413,7 @@ migratecred_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(L #------------------------ mmldif_bin_SOURCES = ldap/servers/slapd/tools/mmldif.c mmldif_bin_CPPFLAGS = $(AM_CPPFLAGS) @openldap_inc@ @ldapsdk_inc@ @nss_inc@ @nspr_inc@ -mmldif_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK) $(SASL_LINK) +mmldif_bin_LDADD = libslapd.la $(NSPR_LINK) $(NSS_LINK) $(SVRCORE_LINK) $(LDAPSDK_LINK_NOTHR) $(SASL_LINK) #------------------------ # ns-slapd
0
f6b0e1841059460d6d0071cc771e3fbe834af393
389ds/389-ds-base
Ticket 48393 - Improve replication config validation Bug Description: There was inconsistent behavior when modifying and adding replication configurations and agreements. There were also a few places where unsigned ints were used for values which made checking for negative values impossible. Fix Description: Added a new function to properly check "number" attribute values. Also forced failure on the actual update if an invalid value was used (previously we would log an error and use some default value). Also made all the int types consistent. https://pagure.io/389-ds-base/issue/48393 Reviewed by: firstyear(Thanks!)
commit f6b0e1841059460d6d0071cc771e3fbe834af393 Author: Mark Reynolds <[email protected]> Date: Fri Nov 3 09:30:01 2017 -0400 Ticket 48393 - Improve replication config validation Bug Description: There was inconsistent behavior when modifying and adding replication configurations and agreements. There were also a few places where unsigned ints were used for values which made checking for negative values impossible. Fix Description: Added a new function to properly check "number" attribute values. Also forced failure on the actual update if an invalid value was used (previously we would log an error and use some default value). Also made all the int types consistent. https://pagure.io/389-ds-base/issue/48393 Reviewed by: firstyear(Thanks!) diff --git a/dirsrvtests/tests/suites/replication/replica_config_test.py b/dirsrvtests/tests/suites/replication/replica_config_test.py new file mode 100644 index 000000000..50ea2ece9 --- /dev/null +++ b/dirsrvtests/tests/suites/replication/replica_config_test.py @@ -0,0 +1,397 @@ +import logging +import pytest +import copy +import os +import ldap +from lib389._constants import * +from lib389 import Entry +from lib389.topologies import topology_st as topo + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + +REPLICA_DN = 'cn=replica,cn="dc=example,dc=com",cn=mapping tree,cn=config' +AGMT_DN = 'cn=test_agreement,cn=replica,cn="dc=example,dc=com",cn=mapping tree,cn=config' +notnum = 'invalid' +too_big = '9223372036854775807' +overflow = '9999999999999999999999999999999999999999999999999999999999999999999' + +replica_dict = {'objectclass': 'top nsDS5Replica'.split(), + 'nsDS5ReplicaRoot': 'dc=example,dc=com', + 'nsDS5ReplicaType': '3', + 'nsDS5Flags': '1', + 'nsDS5ReplicaId': '65535', + 'nsds5ReplicaPurgeDelay': '604800', + 'nsDS5ReplicaBindDN': 'cn=u', + 'cn': 'replica'} + +agmt_dict = {'objectClass': 'top nsDS5ReplicationAgreement'.split(), + 'cn': 'test_agreement', + 'nsDS5ReplicaRoot': 'dc=example,dc=com', + 'nsDS5ReplicaHost': 'localhost.localdomain', + 'nsDS5ReplicaPort': '5555', + 'nsDS5ReplicaBindDN': 'uid=tester', + 'nsds5ReplicaCredentials': 'password', + 'nsDS5ReplicaTransportInfo': 'LDAP', + 'nsDS5ReplicaBindMethod': 'SIMPLE'} + + +repl_add_attrs = [('nsDS5ReplicaType', '-1', '4', overflow, notnum, '1'), + ('nsDS5Flags', '-1', '2', overflow, notnum, '1'), + ('nsDS5ReplicaId', '0', '65536', overflow, notnum, '1'), + ('nsds5ReplicaPurgeDelay', '-2', too_big, overflow, notnum, '1'), + ('nsDS5ReplicaBindDnGroupCheckInterval', '-2', too_big, overflow, notnum, '1'), + ('nsds5ReplicaTombstonePurgeInterval', '-2', too_big, overflow, notnum, '1'), + ('nsds5ReplicaProtocolTimeout', '-1', too_big, overflow, notnum, '1'), + ('nsds5ReplicaReleaseTimeout', '-1', too_big, overflow, notnum, '1'), + ('nsds5ReplicaBackoffMin', '0', too_big, overflow, notnum, '3'), + ('nsds5ReplicaBackoffMax', '0', too_big, overflow, notnum, '6')] + +repl_mod_attrs = [('nsDS5Flags', '-1', '2', overflow, notnum, '1'), + ('nsds5ReplicaPurgeDelay', '-2', too_big, overflow, notnum, '1'), + ('nsDS5ReplicaBindDnGroupCheckInterval', '-2', too_big, overflow, notnum, '1'), + ('nsds5ReplicaTombstonePurgeInterval', '-2', too_big, overflow, notnum, '1'), + ('nsds5ReplicaProtocolTimeout', '-1', too_big, overflow, notnum, '1'), + ('nsds5ReplicaReleaseTimeout', '-1', too_big, overflow, notnum, '1'), + ('nsds5ReplicaBackoffMin', '0', too_big, overflow, notnum, '3'), + ('nsds5ReplicaBackoffMax', '0', too_big, overflow, notnum, '6')] + +agmt_attrs = [('nsds5ReplicaPort', '0', '65536', overflow, notnum, '389'), + ('nsds5ReplicaTimeout', '-1', too_big, overflow, notnum, '6'), + ('nsds5ReplicaBusyWaitTime', '-1', too_big, overflow, notnum, '6'), + ('nsds5ReplicaSessionPauseTime', '-1', too_big, overflow, notnum, '6'), + ('nsds5ReplicaFlowControlWindow', '-1', too_big, overflow, notnum, '6'), + ('nsds5ReplicaFlowControlPause', '-1', too_big, overflow, notnum, '6'), + ('nsds5ReplicaProtocolTimeout', '-1', too_big, overflow, notnum, '6')] + + +def replica_setup(topo): + """Add a valid replica config entry to modify + """ + try: + topo.standalone.delete_s(REPLICA_DN) + except: + pass + + try: + topo.standalone.add_s(Entry((REPLICA_DN, replica_dict))) + except ldap.LDAPError as e: + log.fatal("Failed to add replica entry: " + str(e)) + assert False + + +def replica_reset(topo): + try: + topo.standalone.delete_s(REPLICA_DN) + except: + pass + + +def agmt_setup(topo): + """Add a valid replica config entry to modify + """ + try: + topo.standalone.delete_s(AGMT_DN) + except: + pass + + try: + topo.standalone.add_s(Entry((AGMT_DN, agmt_dict))) + except ldap.LDAPError as e: + log.fatal("Failed to add agreement entry: " + str(e)) + assert False + + +def agmt_reset(topo): + try: + topo.standalone.delete_s(AGMT_DN) + except: + pass + + [email protected]("attr, too_small, too_big, overflow, notnum, valid", repl_add_attrs) +def test_replica_num_add(topo, attr, too_small, too_big, overflow, notnum, valid): + """Test all the number values you can set for a replica config entry + + :id: a8b47d4a-a089-4d70-8070-e6181209bf92 + :setup: standalone instance + :steps: + 1. Use a value that is too small + 2. Use a value that is too big + 3. Use a value that overflows the int + 4. Use a value with character value (not a number) + 5. Use a valid value + :expectedresults: + 1. Add is rejected + 2. Add is rejected + 3. Add is rejected + 4. Add is rejected + 5. Add is allowed + """ + + replica_reset(topo) + + # Test too small + my_replica = copy.deepcopy(replica_dict) + my_replica[attr] = too_small + try: + topo.standalone.add_s(Entry((REPLICA_DN, my_replica))) + log.fatal("Incorrectly allowed to add replica entry with {}:{}".format(attr, too_small)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add replica entry with {}:{} error: {}".format(attr, too_small, str(e))) + + # Test too big + my_replica = copy.deepcopy(replica_dict) + my_replica[attr] = too_big + try: + topo.standalone.add_s(Entry((REPLICA_DN, my_replica))) + log.fatal("Incorrectly allowed to add replica entry with {}:{}".format(attr, too_big)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add replica entry with {}:{} error: {}".format(attr, too_big, str(e))) + + # Test overflow + my_replica = copy.deepcopy(replica_dict) + my_replica[attr] = overflow + try: + topo.standalone.add_s(Entry((REPLICA_DN, my_replica))) + log.fatal("Incorrectly allowed to add replica entry with {}:{}".format(attr, overflow)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add replica entry with {}:{} error: {}".format(attr, overflow, str(e))) + + # test not a number + my_replica = copy.deepcopy(replica_dict) + my_replica[attr] = notnum + try: + topo.standalone.add_s(Entry((REPLICA_DN, my_replica))) + log.fatal("Incorrectly allowed to add replica entry with {}:{}".format(attr, notnum)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add replica entry with {}:{} error: {}".format(attr, notnum, str(e))) + + # Test valid value + my_replica = copy.deepcopy(replica_dict) + my_replica[attr] = valid + try: + topo.standalone.add_s(Entry((REPLICA_DN, my_replica))) + log.info("Correctly allowed to add replica entry with {}: {}".format(attr, valid)) + except ldap.LDAPError as e: + log.fatal("Incorrectly failed to add replica entry with {}: {} error: {}".format(attr, valid, str(e))) + assert False + + [email protected]("attr, too_small, too_big, overflow, notnum, valid", repl_mod_attrs) +def test_replica_num_modify(topo, attr, too_small, too_big, overflow, notnum, valid): + """Test all the number values you can set for a replica config entry + + :id: a8b47d4a-a089-4d70-8070-e6181209bf93 + :setup: standalone instance + :steps: + 1. Replace a value that is too small + 2. Repalce a value that is too big + 3. Replace a value that overflows the int + 4. Replace a value with character value (not a number) + 5. Replace a vlue with a valid value + :expectedresults: + 1. Value is rejected + 2. Value is rejected + 3. Value is rejected + 4. Value is rejected + 5. Value is allowed + """ + + # Value too small + replica_setup(topo) + try: + topo.standalone.modify_s(REPLICA_DN, [(ldap.MOD_REPLACE, attr, too_small)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, too_small)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, too_small)) + + # Value too big + replica_setup(topo) + try: + topo.standalone.modify_s(REPLICA_DN, [(ldap.MOD_REPLACE, attr, too_big)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, too_big)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, too_big)) + + # Value overflow + replica_setup(topo) + try: + topo.standalone.modify_s(REPLICA_DN, [(ldap.MOD_REPLACE, attr, overflow)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, overflow)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, overflow)) + + # Value not a number + replica_setup(topo) + try: + topo.standalone.modify_s(REPLICA_DN, [(ldap.MOD_REPLACE, attr, notnum)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, notnum)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, notnum)) + + # Value is valid + replica_setup(topo) + try: + topo.standalone.modify_s(REPLICA_DN, [(ldap.MOD_REPLACE, attr, valid)]) + log.info('Correctly added valid agreement attribute value: {}:{}'.format(attr, valid)) + except ldap.LDAPError as e: + log.fatal('Valid value for {}:{} was incorrectly rejected. Error {}'.format(attr, valid, str(e))) + assert False + + [email protected]("attr, too_small, too_big, overflow, notnum, valid", agmt_attrs) +def test_agmt_num_add(topo, attr, too_small, too_big, overflow, notnum, valid): + """Test all the number values you can set for a replica config entry + + :id: a8b47d4a-a089-4d70-8070-e6181209bf94 + :setup: standalone instance + :steps: + 1. Use a value that is too small + 2. Use a value that is too big + 3. Use a value that overflows the int + 4. Use a value with character value (not a number) + 5. Use a valid value + :expectedresults: + 1. Add is rejected + 2. Add is rejected + 3. Add is rejected + 4. Add is rejected + 5. Add is allowed + """ + agmt_reset(topo) + + # Test too small + my_agmt = copy.deepcopy(agmt_dict) + my_agmt[attr] = too_small + try: + topo.standalone.add_s(Entry((AGMT_DN, my_agmt))) + log.fatal("Incorrectly allowed to add agreement entry with {}:{}".format(attr, too_small)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add agreement entry with {}:{} error: {}".format(attr, too_small, str(e))) + + # Test too big + my_agmt = copy.deepcopy(agmt_dict) + my_agmt[attr] = too_big + try: + topo.standalone.add_s(Entry((AGMT_DN, my_agmt))) + log.fatal("Incorrectly allowed to add agreement entry with {}:{}".format(attr, too_big)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add agreement entry with {}:{} error: {}".format(attr, too_big, str(e))) + + # Test overflow + my_agmt = copy.deepcopy(agmt_dict) + my_agmt[attr] = overflow + try: + topo.standalone.add_s(Entry((AGMT_DN, my_agmt))) + log.fatal("Incorrectly allowed to add agreement entry with {}:{}".format(attr, overflow)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add agreement entry with {}:{} error: {}".format(attr, overflow, str(e))) + + # test not a number + my_agmt = copy.deepcopy(agmt_dict) + my_agmt[attr] = notnum + try: + topo.standalone.add_s(Entry((AGMT_DN, my_agmt))) + log.fatal("Incorrectly allowed to add agreement entry with {}:{}".format(attr, notnum)) + assert False + except ldap.LDAPError as e: + log.info("Correctly failed to add agreement entry with {}:{} error: {}".format(attr, notnum, str(e))) + + # Test valid value + my_agmt = copy.deepcopy(agmt_dict) + my_agmt[attr] = valid + try: + topo.standalone.add_s(Entry((AGMT_DN, my_agmt))) + log.info("Correctly allowed to add agreement entry with {}: {}".format(attr, valid)) + except ldap.LDAPError as e: + log.fatal("Incorrectly failed to add agreement entry with {}: {} error: {}".format(attr, valid, str(e))) + assert False + + [email protected]("attr, too_small, too_big, overflow, notnum, valid", agmt_attrs) +def test_agmt_num_modify(topo, attr, too_small, too_big, overflow, notnum, valid): + """Test all the number values you can set for a replica config entry + + :id: a8b47d4a-a089-4d70-8070-e6181209bf95 + :setup: standalone instance + :steps: + 1. Replace a value that is too small + 2. Replace a value that is too big + 3. Replace a value that overflows the int + 4. Replace a value with character value (not a number) + 5. Replace a vlue with a valid value + :expectedresults: + 1. Value is rejected + 2. Value is rejected + 3. Value is rejected + 4. Value is rejected + 5. Value is allowed + """ + + # Value too small + agmt_setup(topo) + try: + topo.standalone.modify_s(AGMT_DN, [(ldap.MOD_REPLACE, attr, too_small)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, too_small)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, too_small)) + + # Value too big + agmt_setup(topo) + try: + topo.standalone.modify_s(AGMT_DN, [(ldap.MOD_REPLACE, attr, too_big)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, too_big)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, too_big)) + + # Value overflow + agmt_setup(topo) + try: + topo.standalone.modify_s(AGMT_DN, [(ldap.MOD_REPLACE, attr, overflow)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, overflow)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, overflow)) + + # Value not a number + agmt_setup(topo) + try: + topo.standalone.modify_s(AGMT_DN, [(ldap.MOD_REPLACE, attr, notnum)]) + log.fatal('Invalid value for {}:{} was incorrectly allowed'.format(attr, notnum)) + assert False + except: + log.info('Invalid value for {}:{} was correctly rejected'.format(attr, notnum)) + + # Value is valid + agmt_setup(topo) + try: + topo.standalone.modify_s(AGMT_DN, [(ldap.MOD_REPLACE, attr, valid)]) + except ldap.LDAPError as e: + log.fatal('Valid value for {}:{} was incorrectly rejected. Error {}'.format(attr, valid, str(e))) + assert False + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE) + diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index 246495214..ab124c86c 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -303,6 +303,7 @@ attributeTypes: ( 2.16.840.1.113730.3.1.2331 NAME 'nsslapd-logging-hr-timestamps attributeTypes: ( 2.16.840.1.113730.3.1.2332 NAME 'allowWeakDHParam' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2333 NAME 'nsds5ReplicaReleaseTimeout' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2335 NAME 'nsds5ReplicaIgnoreMissingChange' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2336 NAME 'nsDS5ReplicaBindDnGroupCheckInterval' DESC 'Replication configuration setting for controlling the bind dn group check interval' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE X-ORIGIN 'Netscape Directory Server' ) # # objectclasses # @@ -312,7 +313,7 @@ objectClasses: ( 2.16.840.1.113730.3.2.44 NAME 'nsIndex' DESC 'Netscape defined objectClasses: ( 2.16.840.1.113730.3.2.109 NAME 'nsBackendInstance' DESC 'Netscape defined objectclass' SUP top MUST ( CN ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.110 NAME 'nsMappingTree' DESC 'Netscape defined objectclass' SUP top MUST ( CN ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.104 NAME 'nsContainer' DESC 'Netscape defined objectclass' SUP top MUST ( CN ) X-ORIGIN 'Netscape Directory Server' ) -objectClasses: ( 2.16.840.1.113730.3.2.108 NAME 'nsDS5Replica' DESC 'Netscape defined objectclass' SUP top MUST ( nsDS5ReplicaRoot $ nsDS5ReplicaId ) MAY (cn $ nsds5ReplicaPreciseTombstonePurging $ nsds5ReplicaCleanRUV $ nsds5ReplicaAbortCleanRUV $ nsDS5ReplicaType $ nsDS5ReplicaBindDN $ nsState $ nsDS5ReplicaName $ nsDS5Flags $ nsDS5Task $ nsDS5ReplicaReferral $ nsDS5ReplicaAutoReferral $ nsds5ReplicaPurgeDelay $ nsds5ReplicaTombstonePurgeInterval $ nsds5ReplicaChangeCount $ nsds5ReplicaLegacyConsumer $ nsds5ReplicaProtocolTimeout $ nsds5ReplicaBackoffMin $ nsds5ReplicaBackoffMax $ nsds5ReplicaReleaseTimeout ) X-ORIGIN 'Netscape Directory Server' ) +objectClasses: ( 2.16.840.1.113730.3.2.108 NAME 'nsDS5Replica' DESC 'Replication configuration objectclass' SUP top MUST ( nsDS5ReplicaRoot $ nsDS5ReplicaId ) MAY (cn $ nsds5ReplicaPreciseTombstonePurging $ nsds5ReplicaCleanRUV $ nsds5ReplicaAbortCleanRUV $ nsDS5ReplicaType $ nsDS5ReplicaBindDN $ nsState $ nsDS5ReplicaName $ nsDS5Flags $ nsDS5Task $ nsDS5ReplicaReferral $ nsDS5ReplicaAutoReferral $ nsds5ReplicaPurgeDelay $ nsds5ReplicaTombstonePurgeInterval $ nsds5ReplicaChangeCount $ nsds5ReplicaLegacyConsumer $ nsds5ReplicaProtocolTimeout $ nsds5ReplicaBackoffMin $ nsds5ReplicaBackoffMax $ nsds5ReplicaReleaseTimeout $ nsDS5ReplicaBindDnGroupCheckInterval ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.113 NAME 'nsTombstone' DESC 'Netscape defined objectclass' SUP top MAY ( nstombstonecsn $ nsParentUniqueId $ nscpEntryDN ) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.103 NAME 'nsDS5ReplicationAgreement' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsds5ReplicaCleanRUVNotified $ nsDS5ReplicaHost $ nsDS5ReplicaPort $ nsDS5ReplicaTransportInfo $ nsDS5ReplicaBindDN $ nsDS5ReplicaCredentials $ nsDS5ReplicaBindMethod $ nsDS5ReplicaRoot $ nsDS5ReplicatedAttributeList $ nsDS5ReplicatedAttributeListTotal $ nsDS5ReplicaUpdateSchedule $ nsds5BeginReplicaRefresh $ description $ nsds50ruv $ nsruvReplicaLastModified $ nsds5ReplicaTimeout $ nsds5replicaChangesSentSinceStartup $ nsds5replicaLastUpdateEnd $ nsds5replicaLastUpdateStart $ nsds5replicaLastUpdateStatus $ nsds5replicaUpdateInProgress $ nsds5replicaLastInitEnd $ nsds5ReplicaEnabled $ nsds5replicaLastInitStart $ nsds5replicaLastInitStatus $ nsds5debugreplicatimeout $ nsds5replicaBusyWaitTime $ nsds5ReplicaStripAttrs $ nsds5replicaSessionPauseTime $ nsds5ReplicaProtocolTimeout $ nsds5ReplicaFlowControlWindow $ nsds5ReplicaFlowControlPause $ nsDS5ReplicaWaitForAsyncResults $ nsds5ReplicaIgnoreMissingChange) X-ORIGIN 'Netscape Directory Server' ) objectClasses: ( 2.16.840.1.113730.3.2.39 NAME 'nsslapdConfig' DESC 'Netscape defined objectclass' SUP top MAY ( cn ) X-ORIGIN 'Netscape Directory Server' ) diff --git a/ldap/servers/plugins/replication/repl5.h b/ldap/servers/plugins/replication/repl5.h index 3bd878d4d..c6e79b7e2 100644 --- a/ldap/servers/plugins/replication/repl5.h +++ b/ldap/servers/plugins/replication/repl5.h @@ -330,8 +330,8 @@ void replsupplier_configure(Repl_Supplier *rs, Slapi_PBlock *pb); void replsupplier_start(Repl_Supplier *rs); void replsupplier_stop(Repl_Supplier *rs); void replsupplier_destroy(Repl_Supplier **rs); -void replsupplier_notify(Repl_Supplier *rs, PRUint32 eventmask); -PRUint32 replsupplier_get_status(Repl_Supplier *rs); +void replsupplier_notify(Repl_Supplier *rs, uint32_t eventmask); +uint32_t replsupplier_get_status(Repl_Supplier *rs); /* In repl5_plugins.c */ int multimaster_set_local_purl(void); @@ -383,7 +383,7 @@ int agmt_stop(Repl_Agmt *ra); int agmt_replicate_now(Repl_Agmt *ra); char *agmt_get_hostname(const Repl_Agmt *ra); int agmt_get_port(const Repl_Agmt *ra); -PRUint32 agmt_get_transport_flags(const Repl_Agmt *ra); +uint32_t agmt_get_transport_flags(const Repl_Agmt *ra); char *agmt_get_binddn(const Repl_Agmt *ra); struct berval *agmt_get_credentials(const Repl_Agmt *ra); int agmt_get_bindmethod(const Repl_Agmt *ra); @@ -448,8 +448,8 @@ int agmt_set_attrs_to_strip(Repl_Agmt *ra, Slapi_Entry *e); int agmt_set_timeout(Repl_Agmt *ra, long timeout); int agmt_set_ignoremissing(Repl_Agmt *ra, long ignoremissing); void agmt_update_done(Repl_Agmt *ra, int is_total); -PRUint64 agmt_get_protocol_timeout(Repl_Agmt *agmt); -void agmt_set_protocol_timeout(Repl_Agmt *agmt, PRUint64 timeout); +uint64_t agmt_get_protocol_timeout(Repl_Agmt *agmt); +void agmt_set_protocol_timeout(Repl_Agmt *agmt, uint64_t timeout); void agmt_update_maxcsn(Replica *r, Slapi_DN *sdn, int op, LDAPMod **mods, CSN *csn); void add_agmt_maxcsns(Slapi_Entry *e, Replica *r); void agmt_remove_maxcsn(Repl_Agmt *ra); @@ -532,8 +532,8 @@ void *consumer_connection_extension_constructor(void *object, void *parent); void consumer_connection_extension_destructor(void *ext, void *object, void *parent); /* extension helpers for managing exclusive access */ -consumer_connection_extension *consumer_connection_extension_acquire_exclusive_access(void *conn, PRUint64 connid, int opid); -int consumer_connection_extension_relinquish_exclusive_access(void *conn, PRUint64 connid, int opid, PRBool force); +consumer_connection_extension *consumer_connection_extension_acquire_exclusive_access(void *conn, uint64_t connid, int opid); +int consumer_connection_extension_relinquish_exclusive_access(void *conn, uint64_t connid, int opid, PRBool force); /* mapping tree extension - stores replica object */ typedef struct multimaster_mtnode_extension @@ -666,8 +666,8 @@ Replica *replica_new_from_entry(Slapi_Entry *e, char *errortext, PRBool is_add_o void replica_destroy(void **arg); int replica_subentry_update(Slapi_DN *repl_root, ReplicaId rid); int replica_subentry_check(Slapi_DN *repl_root, ReplicaId rid); -PRBool replica_get_exclusive_access(Replica *r, PRBool *isInc, PRUint64 connid, int opid, const char *locking_purl, char **current_purl); -void replica_relinquish_exclusive_access(Replica *r, PRUint64 connid, int opid); +PRBool replica_get_exclusive_access(Replica *r, PRBool *isInc, uint64_t connid, int opid, const char *locking_purl, char **current_purl); +void replica_relinquish_exclusive_access(Replica *r, uint64_t connid, int opid); PRBool replica_get_tombstone_reap_active(const Replica *r); const Slapi_DN *replica_get_root(const Replica *r); const char *replica_get_name(const Replica *r); @@ -685,11 +685,13 @@ PRBool replica_is_updatedn(Replica *r, const Slapi_DN *sdn); void replica_set_updatedn(Replica *r, const Slapi_ValueSet *vs, int mod_op); void replica_set_groupdn(Replica *r, const Slapi_ValueSet *vs, int mod_op); char *replica_get_generation(const Replica *r); + /* currently supported flags */ #define REPLICA_LOG_CHANGES 0x1 /* enable change logging */ -PRBool replica_is_flag_set(const Replica *r, PRUint32 flag); -void replica_set_flag(Replica *r, PRUint32 flag, PRBool clear); -void replica_replace_flags(Replica *r, PRUint32 flags); + +PRBool replica_is_flag_set(const Replica *r, uint32_t flag); +void replica_set_flag(Replica *r, uint32_t flag, PRBool clear); +void replica_replace_flags(Replica *r, uint32_t flags); void replica_dump(Replica *r); void replica_set_enabled(Replica *r, PRBool enable); Object *replica_get_replica_from_dn(const Slapi_DN *dn); @@ -720,7 +722,7 @@ int replica_delete_by_dn(const char *dn); int replica_is_being_configured(const char *dn); void consumer5_set_mapping_tree_state_for_replica(const Replica *r, RUV *supplierRuv); Object *replica_get_for_backend(const char *be_name); -void replica_set_purge_delay(Replica *r, PRUint32 purge_delay); +void replica_set_purge_delay(Replica *r, uint32_t purge_delay); void replica_set_tombstone_reap_interval(Replica *r, long interval); void replica_update_ruv_consumer(Replica *r, RUV *supplier_ruv); void replica_set_ruv_dirty(Replica *r); @@ -730,20 +732,20 @@ char *replica_get_dn(Replica *r); void replica_check_for_tasks(Replica *r, Slapi_Entry *e); void replica_update_state(time_t when, void *arg); void replica_reset_csn_pl(Replica *r); -PRUint64 replica_get_protocol_timeout(Replica *r); -void replica_set_protocol_timeout(Replica *r, PRUint64 timeout); -PRUint64 replica_get_release_timeout(Replica *r); -void replica_set_release_timeout(Replica *r, PRUint64 timeout); +uint64_t replica_get_protocol_timeout(Replica *r); +void replica_set_protocol_timeout(Replica *r, uint64_t timeout); +uint64_t replica_get_release_timeout(Replica *r); +void replica_set_release_timeout(Replica *r, uint64_t timeout); void replica_set_groupdn_checkinterval(Replica *r, int timeout); -PRUint64 replica_get_backoff_min(Replica *r); -PRUint64 replica_get_backoff_max(Replica *r); -void replica_set_backoff_min(Replica *r, PRUint64 min); -void replica_set_backoff_max(Replica *r, PRUint64 max); +uint64_t replica_get_backoff_min(Replica *r); +uint64_t replica_get_backoff_max(Replica *r); +void replica_set_backoff_min(Replica *r, uint64_t min); +void replica_set_backoff_max(Replica *r, uint64_t max); int replica_get_agmt_count(Replica *r); void replica_incr_agmt_count(Replica *r); void replica_decr_agmt_count(Replica *r); -PRUint64 replica_get_precise_purging(Replica *r); -void replica_set_precise_purging(Replica *r, PRUint64 on_off); +uint64_t replica_get_precise_purging(Replica *r); +void replica_set_precise_purging(Replica *r, uint64_t on_off); PRBool ignore_error_and_keep_going(int error); void replica_check_release_timeout(Replica *r, Slapi_PBlock *pb); void replica_lock_replica(Replica *r); @@ -764,8 +766,8 @@ void replica_unlock_replica(Replica *r); is active, RECV should back off. And vice versa. But SEND can coexist. */ #define REPLICA_TOTAL_EXCL_RECV 32 /* ditto */ -PRBool replica_is_state_flag_set(Replica *r, PRInt32 flag); -void replica_set_state_flag(Replica *r, PRUint32 flag, PRBool clear); +PRBool replica_is_state_flag_set(Replica *r, int32_t flag); +void replica_set_state_flag(Replica *r, uint32_t flag, PRBool clear); void replica_set_tombstone_reap_stop(Replica *r, PRBool val); void replica_enable_replication(Replica *r); void replica_disable_replication(Replica *r, Object *r_obj); @@ -836,6 +838,8 @@ LDAPControl *create_managedsait_control(void); LDAPControl *create_backend_control(Slapi_DN *sdn); void repl_set_mtn_state_and_referrals(const Slapi_DN *sdn, const char *mtn_state, const RUV *ruv, char **ruv_referrals, char **other_referrals); void repl_set_repl_plugin_path(const char *path); +int repl_config_valid_num(const char *config_attr, char *config_attr_value, int64_t min, int64_t max, + int *returncode, char *errortext, int64_t *retval); /* repl5_updatedn_list.c */ typedef void *ReplicaUpdateDNList; diff --git a/ldap/servers/plugins/replication/repl5_agmt.c b/ldap/servers/plugins/replication/repl5_agmt.c index e2ab320e4..78fb91ae6 100644 --- a/ldap/servers/plugins/replication/repl5_agmt.c +++ b/ldap/servers/plugins/replication/repl5_agmt.c @@ -65,31 +65,31 @@ struct changecounter { ReplicaId rid; - PRUint32 num_replayed; - PRUint32 num_skipped; + uint32_t num_replayed; + uint32_t num_skipped; }; typedef struct repl5agmt { char *hostname; /* remote hostname */ - int port; /* port of remote server */ - PRUint32 transport_flags; /* SSL, TLS, etc. */ + int64_t port; /* port of remote server */ + uint32_t transport_flags; /* SSL, TLS, etc. */ char *binddn; /* DN to bind as */ struct berval *creds; /* Password, or certificate */ - int bindmethod; /* Bind method - simple, SSL */ + int64_t bindmethod; /* Bind method - simple, SSL */ Slapi_DN *replarea; /* DN of replicated area */ char **frac_attrs; /* list of fractional attributes to be replicated */ char **frac_attrs_total; /* list of fractional attributes to be replicated for total update protocol */ PRBool frac_attr_total_defined; /* TRUE if frac_attrs_total is defined */ Schedule *schedule; /* Scheduling information */ - int auto_initialize; /* 1 = automatically re-initialize replica */ + int64_t auto_initialize; /* 1 = automatically re-initialize replica */ const Slapi_DN *dn; /* DN of replication agreement entry */ const Slapi_RDN *rdn; /* RDN of replication agreement entry */ char *long_name; /* Long name (rdn + host, port) of entry, for logging */ Repl_Protocol *protocol; /* Protocol object - manages protocol */ struct changecounter **changecounters; /* changes sent/skipped since server start up */ - int num_changecounters; - int max_changecounters; + int64_t num_changecounters; + int64_t max_changecounters; time_t last_update_start_time; /* Local start time of last update session */ time_t last_update_end_time; /* Local end time of last update session */ char last_update_status[STATUS_LEN]; /* Status of last update. Format = numeric code <space> textual description */ @@ -102,35 +102,35 @@ typedef struct repl5agmt Object *consumerRUV; /* last RUV received from the consumer - used for changelog purging */ CSN *consumerSchemaCSN; /* last schema CSN received from the consumer */ ReplicaId consumerRID; /* indicates if the consumer is the originator of a CSN */ - int tmpConsumerRID; /* Indicates the consumer rid was set from the agmt maxcsn - it should be refreshed */ - long timeout; /* timeout (in seconds) for outbound LDAP connections to remote server */ + int64_t tmpConsumerRID; /* Indicates the consumer rid was set from the agmt maxcsn - it should be refreshed */ + int64_t timeout; /* timeout (in seconds) for outbound LDAP connections to remote server */ PRBool stop_in_progress; /* set by agmt_stop when shutting down */ - long busywaittime; /* time in seconds to wait after getting a REPLICA BUSY from the consumer - - to allow another supplier to finish sending its updates - - if set to 0, this means to use the default value if we get a busy - signal from the consumer */ - long pausetime; /* time in seconds to pause after sending updates - - to allow another supplier to send its updates - - should be greater than busywaittime - - if set to 0, this means do not pause */ + int64_t busywaittime; /* time in seconds to wait after getting a REPLICA BUSY from the consumer - + * to allow another supplier to finish sending its updates - + * if set to 0, this means to use the default value if we get a busy + * signal from the consumer + */ + int64_t pausetime; /* time in seconds to pause after sending updates - + * to allow another supplier to send its updates - + * should be greater than busywaittime - + * if set to 0, this means do not pause + */ void *priv; /* private data, used for windows-specific agreement data - for sync agreements or for replication session plug-in - private data for normal replication agreements */ + * for sync agreements or for replication session plug-in + * private data for normal replication agreements + */ char **attrs_to_strip; /* for fractional replication, if a "mod" is empty, strip out these attributes: - * modifiersname, modifytimestamp, internalModifiersname, internalModifyTimestamp, etc */ - int agreement_type; + * modifiersname, modifytimestamp, internalModifiersname, internalModifyTimestamp, etc */ + int64_t agreement_type; Slapi_Counter *protocol_timeout; - char *maxcsn; /* agmt max csn */ - long flowControlWindow; /* This is the maximum number of entries - * sent without acknowledgment - */ - long flowControlPause; /* When nb of not acknowledged entries overpass totalUpdateWindow - * This is the duration (in msec) that the RA will pause before sending the next entry - */ - long ignoreMissingChange; /* if set replication will try to continue even if change cannot be found in changelog */ - Slapi_RWLock *attr_lock; /* RW lock for all the stripped attrs */ - int WaitForAsyncResults; /* Pass to DS_Sleep(PR_MillisecondsToInterval(WaitForAsyncResults)) - * in repl5_inc_waitfor_async_results */ + char *maxcsn; /* agmt max csn */ + int64_t flowControlWindow; /* This is the maximum number of entries sent without acknowledgment */ + int64_t flowControlPause; /* When nb of not acknowledged entries overpass totalUpdateWindow + * This is the duration (in msec) that the RA will pause before sending the next entry */ + int64_t ignoreMissingChange; /* if set replication will try to continue even if change cannot be found in changelog */ + Slapi_RWLock *attr_lock; /* RW lock for all the stripped attrs */ + int64_t WaitForAsyncResults; /* Pass to DS_Sleep(PR_MillisecondsToInterval(WaitForAsyncResults)) + * in repl5_inc_waitfor_async_results */ } repl5agmt; /* Forward declarations */ @@ -182,7 +182,7 @@ agmt_is_valid(Repl_Agmt *ra) } if (ra->port <= 0) { slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "agmt_is_valid - Replication agreement \"%s\" " - "is malformed: invalid port number %d.\n", + "is malformed: invalid port number %ld.\n", slapi_sdn_get_dn(ra->dn), ra->port); return_value = 0; } @@ -241,10 +241,14 @@ agmt_new_from_entry(Slapi_Entry *e) { Repl_Agmt *ra; Slapi_Attr *sattr; + char errormsg[SLAPI_DSE_RETURNTEXT_SIZE]; char *tmpstr; char **denied_attrs = NULL; char *auto_initialize = NULL; char *val_nsds5BeginReplicaRefresh = "start"; + char *val = NULL; + int64_t ptimeout = 0; + int rc = 0; ra = (Repl_Agmt *)slapi_ch_calloc(1, sizeof(repl5agmt)); if ((ra->lock = PR_NewLock()) == NULL) { @@ -283,8 +287,17 @@ agmt_new_from_entry(Slapi_Entry *e) /* Host name of remote replica */ ra->hostname = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaHost); + /* Port number for remote replica instance */ - ra->port = slapi_entry_attr_get_int(e, type_nsds5ReplicaPort); + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaPort))){ + int64_t port; + if (repl_config_valid_num(type_nsds5ReplicaPort, val, 1, 65535, &rc, errormsg, &port) != 0) { + goto loser; + } + slapi_ch_free_string(&val); + ra->port = port; + } + /* SSL, TLS, or other transport stuff */ ra->transport_flags = 0; (void)agmt_set_transportinfo_no_lock(ra, e); @@ -313,29 +326,35 @@ agmt_new_from_entry(Slapi_Entry *e) /* timeout. */ ra->timeout = DEFAULT_TIMEOUT; - if (slapi_entry_attr_find(e, type_nsds5ReplicaTimeout, &sattr) == 0) { - Slapi_Value *sval; - if (slapi_attr_first_value(sattr, &sval) == 0) { - ra->timeout = slapi_value_get_long(sval); + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaTimeout))){ + int64_t timeout; + if (repl_config_valid_num(type_nsds5ReplicaTimeout, val, 0, INT_MAX, &rc, errormsg, &timeout) != 0) { + goto loser; } + slapi_ch_free_string(&val); + ra->timeout = timeout; } /* flow control update window. */ ra->flowControlWindow = DEFAULT_FLOWCONTROL_WINDOW; - if (slapi_entry_attr_find(e, type_nsds5ReplicaFlowControlWindow, &sattr) == 0) { - Slapi_Value *sval; - if (slapi_attr_first_value(sattr, &sval) == 0) { - ra->flowControlWindow = slapi_value_get_long(sval); + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaFlowControlWindow))){ + int64_t flow; + if (repl_config_valid_num(type_nsds5ReplicaTimeout, val, 0, INT_MAX, &rc, errormsg, &flow) != 0) { + goto loser; } + slapi_ch_free_string(&val); + ra->flowControlWindow = flow; } /* flow control update pause. */ ra->flowControlPause = DEFAULT_FLOWCONTROL_PAUSE; - if (slapi_entry_attr_find(e, type_nsds5ReplicaFlowControlPause, &sattr) == 0) { - Slapi_Value *sval; - if (slapi_attr_first_value(sattr, &sval) == 0) { - ra->flowControlPause = slapi_value_get_long(sval); + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaFlowControlPause))){ + int64_t pause; + if (repl_config_valid_num(type_nsds5ReplicaFlowControlPause, val, 0, INT_MAX, &rc, errormsg, &pause) != 0) { + goto loser; } + slapi_ch_free_string(&val); + ra->flowControlPause = pause; } /* continue on missing change ? */ @@ -357,7 +376,6 @@ agmt_new_from_entry(Slapi_Entry *e) if (NULL != tmpstr) { Object *repl_obj; Replica *replica; - PRUint64 ptimeout = 0; ra->replarea = slapi_sdn_new_dn_passin(tmpstr); @@ -367,14 +385,18 @@ agmt_new_from_entry(Slapi_Entry *e) replica_incr_agmt_count(replica); } } + } - /* If this agmt has its own timeout, grab it, otherwise use the replica's protocol timeout */ - ptimeout = slapi_entry_attr_get_int(e, type_replicaProtocolTimeout); - if (ptimeout) { - slapi_counter_set_value(ra->protocol_timeout, ptimeout); + /* If this agmt has its own timeout, grab it, otherwise use the replica's protocol timeout */ + if ((val = slapi_entry_attr_get_charptr(e, type_replicaProtocolTimeout))){ + if (repl_config_valid_num(type_replicaProtocolTimeout, val, 0, INT_MAX, &rc, errormsg, &ptimeout) != 0) { + goto loser; } + slapi_ch_free_string(&val); + slapi_counter_set_value(ra->protocol_timeout, ptimeout); } + /* Replica enabled */ tmpstr = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaEnabled); if (NULL != tmpstr) { @@ -384,9 +406,8 @@ agmt_new_from_entry(Slapi_Entry *e) ra->is_enabled = PR_TRUE; } else { slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "agmt_new_from_entry - " - "Warning invalid value for nsds5ReplicaEnabled (%s), value must be \"on\" or \"off\". " - "Ignoring this repl agreement.\n", - tmpstr); + "Warning invalid value for nsds5ReplicaEnabled (%s), value must be \"on\" or \"off\". " + "Ignoring this repl agreement.\n", tmpstr); slapi_ch_free_string(&tmpstr); goto loser; } @@ -402,11 +423,24 @@ agmt_new_from_entry(Slapi_Entry *e) } /* busy wait time - time to wait after getting REPLICA BUSY from consumer */ - ra->busywaittime = slapi_entry_attr_get_long(e, type_nsds5ReplicaBusyWaitTime); + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaBusyWaitTime))){ + int64_t busytime = 0; + if (repl_config_valid_num(type_nsds5ReplicaBusyWaitTime, val, 0, INT_MAX, &rc, errormsg, &busytime) != 0) { + goto loser; + } + slapi_ch_free_string(&val); + ra->busywaittime = busytime; + } /* pause time - time to pause after a session has ended */ - ra->pausetime = slapi_entry_attr_get_long(e, type_nsds5ReplicaSessionPauseTime); - + if ((val = slapi_entry_attr_get_charptr(e, type_nsds5ReplicaSessionPauseTime))){ + int64_t pausetime = 0; + if (repl_config_valid_num(type_nsds5ReplicaSessionPauseTime, val, 0, INT_MAX, &rc, errormsg, &pausetime) != 0) { + goto loser; + } + slapi_ch_free_string(&val); + ra->pausetime = pausetime; + } /* consumer's RUV */ if (slapi_entry_attr_find(e, type_ruvElement, &sattr) == 0) { RUV *ruv; @@ -434,7 +468,7 @@ agmt_new_from_entry(Slapi_Entry *e) if (dot) { *dot = '\0'; } - ra->long_name = slapi_ch_smprintf("agmt=\"%s\" (%s:%d)", agmtname, hostname, ra->port); + ra->long_name = slapi_ch_smprintf("agmt=\"%s\" (%s:%ld)", agmtname, hostname, ra->port); } /* DBDB: review this code */ @@ -534,6 +568,9 @@ agmt_new_from_entry(Slapi_Entry *e) return ra; loser: + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, + "agmt_new_from_entry - Failed to parse agreement, skipping.\n"); + slapi_ch_free_string(&val); agmt_delete((void **)&ra); return NULL; } @@ -754,10 +791,10 @@ agmt_start(Repl_Agmt *ra) char buf[BUFSIZ]; char unavail_buf[BUFSIZ]; - PR_snprintf(buf, BUFSIZ, "%s;%s;%s;%d;", slapi_sdn_get_dn(repl_sdn), + PR_snprintf(buf, BUFSIZ, "%s;%s;%s;%ld;", slapi_sdn_get_dn(repl_sdn), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(ra->rdn)), ra->hostname, ra->port); - PR_snprintf(unavail_buf, BUFSIZ, "%s;%s;%s;%d;unavailable", slapi_sdn_get_dn(repl_sdn), + PR_snprintf(unavail_buf, BUFSIZ, "%s;%s;%s;%ld;unavailable", slapi_sdn_get_dn(repl_sdn), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(ra->rdn)), ra->hostname, ra->port); if (strstr(maxcsns[i], buf) || strstr(maxcsns[i], unavail_buf)) { @@ -901,7 +938,7 @@ agmt_get_port(const Repl_Agmt *ra) /* * Return the transport flags for this agreement. */ -PRUint32 +uint32_t agmt_get_transport_flags(const Repl_Agmt *ra) { unsigned int return_value; @@ -2919,7 +2956,7 @@ agmt_update_done(Repl_Agmt *agmt, int is_total) } } -PRUint64 +uint64_t agmt_get_protocol_timeout(Repl_Agmt *agmt) { if (agmt) { @@ -2930,7 +2967,7 @@ agmt_get_protocol_timeout(Repl_Agmt *agmt) } void -agmt_set_protocol_timeout(Repl_Agmt *agmt, PRUint64 timeout) +agmt_set_protocol_timeout(Repl_Agmt *agmt, uint64_t timeout) { if (agmt) { slapi_counter_set_value(agmt->protocol_timeout, timeout); @@ -2992,11 +3029,11 @@ agmt_update_maxcsn(Replica *r, Slapi_DN *sdn, int op, LDAPMod **mods, CSN *csn) * temporarily mark it as "unavailable". */ slapi_ch_free_string(&agmt->maxcsn); - agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%d;unavailable", slapi_sdn_get_dn(agmt->replarea), + agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%ld;unavailable", slapi_sdn_get_dn(agmt->replarea), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(agmt->rdn)), agmt->hostname, agmt->port); } else if (rid == oprid) { slapi_ch_free_string(&agmt->maxcsn); - agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%d;%d;%s", slapi_sdn_get_dn(agmt->replarea), + agmt->maxcsn = slapi_ch_smprintf("%s;%s;%s;%ld;%d;%s", slapi_sdn_get_dn(agmt->replarea), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(agmt->rdn)), agmt->hostname, agmt->port, agmt->consumerRID, maxcsn); } @@ -3190,10 +3227,10 @@ agmt_remove_maxcsn(Repl_Agmt *ra) char unavail_buf[BUFSIZ]; struct berval val; - PR_snprintf(buf, BUFSIZ, "%s;%s;%s;%d;", slapi_sdn_get_dn(ra->replarea), + PR_snprintf(buf, BUFSIZ, "%s;%s;%s;%ld;", slapi_sdn_get_dn(ra->replarea), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(ra->rdn)), ra->hostname, ra->port); - PR_snprintf(unavail_buf, BUFSIZ, "%s;%s;%s;%d;unavailable", + PR_snprintf(unavail_buf, BUFSIZ, "%s;%s;%s;%ld;unavailable", slapi_sdn_get_dn(ra->replarea), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(ra->rdn)), ra->hostname, ra->port); diff --git a/ldap/servers/plugins/replication/repl5_replica.c b/ldap/servers/plugins/replication/repl5_replica.c index 92f847f24..e5296bf1c 100644 --- a/ldap/servers/plugins/replication/repl5_replica.c +++ b/ldap/servers/plugins/replication/repl5_replica.c @@ -33,42 +33,40 @@ struct replica Slapi_DN *repl_root; /* top of the replicated are */ char *repl_name; /* unique replica name */ PRBool new_name; /* new name was generated - need to be saved */ - ReplicaUpdateDNList updatedn_list; /* list of dns with which a supplier should bind - to update this replica */ - Slapi_ValueSet *updatedn_groups; /* set of groups whose memebers are - * allowed to update replica */ + ReplicaUpdateDNList updatedn_list; /* list of dns with which a supplier should bind to update this replica */ + Slapi_ValueSet *updatedn_groups; /* set of groups whose memebers are allowed to update replica */ ReplicaUpdateDNList groupdn_list; /* exploded listof dns from update group */ - PRUint32 updatedn_group_last_check; - int updatedn_group_check_interval; - ReplicaType repl_type; /* is this replica read-only ? */ - ReplicaId repl_rid; /* replicaID */ - Object *repl_ruv; /* replica update vector */ - PRBool repl_ruv_dirty; /* Dirty flag for ruv */ - CSNPL *min_csn_pl; /* Pending list for minimal CSN */ - void *csn_pl_reg_id; /* registration assignment for csn callbacks */ - unsigned long repl_state_flags; /* state flags */ - PRUint32 repl_flags; /* persistent, externally visible flags */ - PRMonitor *repl_lock; /* protects entire structure */ - Slapi_Eq_Context repl_eqcxt_rs; /* context to cancel event that saves ruv */ - Slapi_Eq_Context repl_eqcxt_tr; /* context to cancel event that reaps tombstones */ - Object *repl_csngen; /* CSN generator for this replica */ - PRBool repl_csn_assigned; /* Flag set when new csn is assigned. */ - PRUint32 repl_purge_delay; /* When purgeable, CSNs are held on to for this many extra seconds */ - PRBool tombstone_reap_stop; /* TRUE when the tombstone reaper should stop */ - PRBool tombstone_reap_active; /* TRUE when the tombstone reaper is running */ - long tombstone_reap_interval; /* Time in seconds between tombstone reaping */ - Slapi_ValueSet *repl_referral; /* A list of administrator provided referral URLs */ - PRBool state_update_inprogress; /* replica state is being updated */ - PRLock *agmt_lock; /* protects agreement creation, start and stop */ - char *locking_purl; /* supplier who has exclusive access */ - uint64_t locking_conn; /* The supplier's connection id */ - Slapi_Counter *protocol_timeout; /* protocol shutdown timeout */ - Slapi_Counter *backoff_min; /* backoff retry minimum */ - Slapi_Counter *backoff_max; /* backoff retry maximum */ - Slapi_Counter *precise_purging; /* Enable precise tombstone purging */ - PRUint64 agmt_count; /* Number of agmts */ - Slapi_Counter *release_timeout; /* The amount of time to wait before releasing active replica */ - PRUint64 abort_session; /* Abort the current replica session */ + uint32_t updatedn_group_last_check; /* the time of the last group check */ + int64_t updatedn_group_check_interval; /* the group check interval */ + ReplicaType repl_type; /* is this replica read-only ? */ + ReplicaId repl_rid; /* replicaID */ + Object *repl_ruv; /* replica update vector */ + PRBool repl_ruv_dirty; /* Dirty flag for ruv */ + CSNPL *min_csn_pl; /* Pending list for minimal CSN */ + void *csn_pl_reg_id; /* registration assignment for csn callbacks */ + unsigned long repl_state_flags; /* state flags */ + uint32_t repl_flags; /* persistent, externally visible flags */ + PRMonitor *repl_lock; /* protects entire structure */ + Slapi_Eq_Context repl_eqcxt_rs; /* context to cancel event that saves ruv */ + Slapi_Eq_Context repl_eqcxt_tr; /* context to cancel event that reaps tombstones */ + Object *repl_csngen; /* CSN generator for this replica */ + PRBool repl_csn_assigned; /* Flag set when new csn is assigned. */ + int64_t repl_purge_delay; /* When purgeable, CSNs are held on to for this many extra seconds */ + PRBool tombstone_reap_stop; /* TRUE when the tombstone reaper should stop */ + PRBool tombstone_reap_active; /* TRUE when the tombstone reaper is running */ + int64_t tombstone_reap_interval; /* Time in seconds between tombstone reaping */ + Slapi_ValueSet *repl_referral; /* A list of administrator provided referral URLs */ + PRBool state_update_inprogress; /* replica state is being updated */ + PRLock *agmt_lock; /* protects agreement creation, start and stop */ + char *locking_purl; /* supplier who has exclusive access */ + uint64_t locking_conn; /* The supplier's connection id */ + Slapi_Counter *protocol_timeout; /* protocol shutdown timeout */ + Slapi_Counter *backoff_min; /* backoff retry minimum */ + Slapi_Counter *backoff_max; /* backoff retry maximum */ + Slapi_Counter *precise_purging; /* Enable precise tombstone purging */ + uint64_t agmt_count; /* Number of agmts */ + Slapi_Counter *release_timeout; /* The amount of time to wait before releasing active replica */ + uint64_t abort_session; /* Abort the current replica session */ }; @@ -532,7 +530,7 @@ replica_subentry_update(Slapi_DN *repl_root, ReplicaId rid) * current_purl is the supplier who already has access, if any */ PRBool -replica_get_exclusive_access(Replica *r, PRBool *isInc, PRUint64 connid, int opid, const char *locking_purl, char **current_purl) +replica_get_exclusive_access(Replica *r, PRBool *isInc, uint64_t connid, int opid, const char *locking_purl, char **current_purl) { PRBool rval = PR_TRUE; @@ -608,7 +606,7 @@ done: * Relinquish exclusive access to the replica */ void -replica_relinquish_exclusive_access(Replica *r, PRUint64 connid, int opid) +replica_relinquish_exclusive_access(Replica *r, uint64_t connid, int opid) { PRBool isInc; @@ -915,7 +913,7 @@ replica_get_type(const Replica *r) return r->repl_type; } -PRUint64 +uint64_t replica_get_protocol_timeout(Replica *r) { if (r) { @@ -925,7 +923,7 @@ replica_get_protocol_timeout(Replica *r) } } -PRUint64 +uint64_t replica_get_release_timeout(Replica *r) { if (r) { @@ -936,7 +934,7 @@ replica_get_release_timeout(Replica *r) } void -replica_set_release_timeout(Replica *r, PRUint64 limit) +replica_set_release_timeout(Replica *r, uint64_t limit) { if (r) { slapi_counter_set_value(r->release_timeout, limit); @@ -944,7 +942,7 @@ replica_set_release_timeout(Replica *r, PRUint64 limit) } void -replica_set_protocol_timeout(Replica *r, PRUint64 timeout) +replica_set_protocol_timeout(Replica *r, uint64_t timeout) { if (r) { slapi_counter_set_value(r->protocol_timeout, timeout); @@ -1182,7 +1180,7 @@ replica_get_generation(const Replica *r) } PRBool -replica_is_flag_set(const Replica *r, PRUint32 flag) +replica_is_flag_set(const Replica *r, uint32_t flag) { if (r) return (r->repl_flags & flag); @@ -1191,7 +1189,7 @@ replica_is_flag_set(const Replica *r, PRUint32 flag) } void -replica_set_flag(Replica *r, PRUint32 flag, PRBool clear) +replica_set_flag(Replica *r, uint32_t flag, PRBool clear) { if (r == NULL) return; @@ -1208,7 +1206,7 @@ replica_set_flag(Replica *r, PRUint32 flag, PRBool clear) } void -replica_replace_flags(Replica *r, PRUint32 flags) +replica_replace_flags(Replica *r, uint32_t flags) { if (r) { replica_lock(r->repl_lock); @@ -1829,17 +1827,18 @@ _replica_check_validity(const Replica *r) static int _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) { - Slapi_Attr *a = NULL; Slapi_Attr *attr; CSNGen *gen; char *precise_purging = NULL; char buf[SLAPI_DSE_RETURNTEXT_SIZE]; char *errormsg = errortext ? errortext : buf; char *val; - int backoff_min; - int backoff_max; - int ptimeout = 0; - int release_timeout = 0; + int64_t backoff_min; + int64_t backoff_max; + int64_t ptimeout = 0; + int64_t release_timeout = 0; + int64_t interval = 0; + int64_t rtype = 0; int rc; PR_ASSERT(r && e); @@ -1847,7 +1846,7 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) /* get replica root */ val = slapi_entry_attr_get_charptr(e, attr_replicaRoot); if (val == NULL) { - PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, "Failed to retrieve %s attribute from (%s)\n", + PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, "Failed to retrieve %s attribute from (%s)", attr_replicaRoot, (char *)slapi_entry_get_dn((Slapi_Entry *)e)); slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - %s\n", @@ -1858,66 +1857,94 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) r->repl_root = slapi_sdn_new_dn_passin(val); /* get replica type */ - val = slapi_entry_attr_get_charptr(e, attr_replicaType); - if (val) { - r->repl_type = atoi(val); - slapi_ch_free((void **)&val); + if (slapi_entry_attr_exists(e, attr_replicaType)) { + if ((val = slapi_entry_attr_get_charptr(e, attr_replicaType))) { + if (repl_config_valid_num(attr_replicaType, val, 0, REPLICA_TYPE_UPDATABLE, &rc, errormsg, &rtype) != 0) { + slapi_ch_free_string(&val); + return -1; + } + r->repl_type = rtype; + slapi_ch_free_string(&val); + } else { + r->repl_type = REPLICA_TYPE_READONLY; + } } else { r->repl_type = REPLICA_TYPE_READONLY; } - /* grab and validate the backoff retry settings */ + /* grab and validate the backoff min retry settings */ if (slapi_entry_attr_exists(e, type_replicaBackoffMin)) { - backoff_min = slapi_entry_attr_get_int(e, type_replicaBackoffMin); - if (backoff_min <= 0) { - slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name, "_replica_init_from_config - " - "Invalid value for %s: %d Using default value (%d)\n", - type_replicaBackoffMin, backoff_min, PROTOCOL_BACKOFF_MINIMUM); + if ((val = slapi_entry_attr_get_charptr(e, type_replicaBackoffMin))) { + if (repl_config_valid_num(type_replicaBackoffMin, val, 1, INT_MAX, &rc, errormsg, &backoff_min) != 0) { + slapi_ch_free_string(&val); + return -1; + } + slapi_ch_free_string(&val); + } else { backoff_min = PROTOCOL_BACKOFF_MINIMUM; } } else { backoff_min = PROTOCOL_BACKOFF_MINIMUM; } + /* grab and validate the backoff max retry settings */ if (slapi_entry_attr_exists(e, type_replicaBackoffMax)) { - backoff_max = slapi_entry_attr_get_int(e, type_replicaBackoffMax); - if (backoff_max <= 0) { - slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name, "_replica_init_from_config - " - "Invalid value for %s: %d Using default value (%d)\n", - type_replicaBackoffMax, backoff_max, PROTOCOL_BACKOFF_MAXIMUM); + if ((val = slapi_entry_attr_get_charptr(e, type_replicaBackoffMax))) { + if (repl_config_valid_num(type_replicaBackoffMax, val, 1, INT_MAX, &rc, errormsg, &backoff_max) != 0) { + slapi_ch_free_string(&val); + return -1; + } + slapi_ch_free_string(&val); + } else { backoff_max = PROTOCOL_BACKOFF_MAXIMUM; } } else { backoff_max = PROTOCOL_BACKOFF_MAXIMUM; } + /* Verify backoff min and max work together */ if (backoff_min > backoff_max) { - /* Ok these values are invalid, reset back the defaults */ - slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name, "_replica_init_from_config - " - "Backoff minimum (%d) can not be greater than " - "the backoff maximum (%d). Using default values: min (%d) max (%d)\n", - backoff_min, backoff_max, PROTOCOL_BACKOFF_MINIMUM, PROTOCOL_BACKOFF_MAXIMUM); - slapi_counter_set_value(r->backoff_min, PROTOCOL_BACKOFF_MINIMUM); - slapi_counter_set_value(r->backoff_max, PROTOCOL_BACKOFF_MAXIMUM); + PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, + "Backoff minimum (%ld) can not be greater than the backoff maximum (%ld).", + backoff_min, backoff_max); + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - " + "%s\n", errormsg); + return -1; } else { slapi_counter_set_value(r->backoff_min, backoff_min); slapi_counter_set_value(r->backoff_max, backoff_max); } /* get the protocol timeout */ - ptimeout = slapi_entry_attr_get_int(e, type_replicaProtocolTimeout); - if (ptimeout <= 0) { - slapi_counter_set_value(r->protocol_timeout, DEFAULT_PROTOCOL_TIMEOUT); + if (slapi_entry_attr_exists(e, type_replicaProtocolTimeout)) { + if ((val = slapi_entry_attr_get_charptr(e, type_replicaProtocolTimeout))) { + if (repl_config_valid_num(type_replicaProtocolTimeout, val, 0, INT_MAX, &rc, errormsg, &ptimeout) != 0) { + slapi_ch_free_string(&val); + return -1; + } + slapi_ch_free_string(&val); + slapi_counter_set_value(r->protocol_timeout, ptimeout); + } else { + slapi_counter_set_value(r->protocol_timeout, DEFAULT_PROTOCOL_TIMEOUT); + } } else { - slapi_counter_set_value(r->protocol_timeout, ptimeout); + slapi_counter_set_value(r->protocol_timeout, DEFAULT_PROTOCOL_TIMEOUT); } /* Get the release timeout */ - release_timeout = slapi_entry_attr_get_int(e, type_replicaReleaseTimeout); - if (release_timeout <= 0) { - slapi_counter_set_value(r->release_timeout, 0); + if (slapi_entry_attr_exists(e, type_replicaReleaseTimeout)) { + if ((val = slapi_entry_attr_get_charptr(e, type_replicaReleaseTimeout))) { + if (repl_config_valid_num(type_replicaReleaseTimeout, val, 0, INT_MAX, &rc, errortext, &release_timeout) != 0) { + slapi_ch_free_string(&val); + return -1; + } + slapi_counter_set_value(r->release_timeout, release_timeout); + slapi_ch_free_string(&val); + } else { + slapi_counter_set_value(r->release_timeout, 0); + } } else { - slapi_counter_set_value(r->release_timeout, release_timeout); + slapi_counter_set_value(r->release_timeout, 0); } /* check for precise tombstone purging */ @@ -1929,10 +1956,11 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) slapi_counter_set_value(r->precise_purging, 0); } else { /* Invalid value */ - slapi_log_err(SLAPI_LOG_WARNING, repl_plugin_name, "_replica_init_from_config - " - "Invalid value for %s: %s Using default value (off)\n", - type_replicaPrecisePurge, precise_purging); - slapi_counter_set_value(r->precise_purging, 0); + PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, "Invalid value for %s: %s", + type_replicaPrecisePurge, precise_purging); + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "_replica_init_from_config - " + "%s\n", errormsg); + return -1; } slapi_ch_free_string(&precise_purging); } else { @@ -1940,7 +1968,19 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) } /* get replica flags */ - r->repl_flags = slapi_entry_attr_get_ulong(e, attr_flags); + if (slapi_entry_attr_exists(e, attr_flags)) { + int64_t rflags; + if((val = slapi_entry_attr_get_charptr(e, attr_flags))) { + if (repl_config_valid_num(attr_flags, val, 0, 1, &rc, errortext, &rflags) != 0) { + return -1; + } + r->repl_flags = (uint32_t)rflags; + } else { + r->repl_flags = 0; + } + } else { + r->repl_flags = 0; + } /* * Get replicaid @@ -1955,20 +1995,13 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) else if (r->repl_type == REPLICA_TYPE_UPDATABLE || r->repl_type == REPLICA_TYPE_PRIMARY) { if ((val = slapi_entry_attr_get_charptr(e, attr_replicaId))) { - int temprid = atoi(val); - slapi_ch_free((void **)&val); - if (temprid <= 0 || temprid >= READ_ONLY_REPLICA_ID) { - PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s must have a value greater than 0 " - "and less than %d: entry %s", - attr_replicaId, READ_ONLY_REPLICA_ID, - (char *)slapi_entry_get_dn((Slapi_Entry *)e)); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, - "_replica_init_from_config - %s\n", errormsg); + int64_t rid; + if (repl_config_valid_num(attr_replicaId, val, 1, 65535, &rc, errormsg, &rid) != 0) { + slapi_ch_free_string(&val); return -1; - } else { - r->repl_rid = (ReplicaId)temprid; } + r->repl_rid = (ReplicaId)rid; + slapi_ch_free_string(&val); } else { PR_snprintf(errormsg, SLAPI_DSE_RETURNTEXT_SIZE, "Failed to retrieve required %s attribute from %s", @@ -2003,10 +2036,13 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) r->groupdn_list = replica_groupdn_list_new(r->updatedn_groups); r->updatedn_group_last_check = time(NULL); /* get groupdn check interval */ - val = slapi_entry_attr_get_charptr(e, attr_replicaBindDnGroupCheckInterval); - if (val) { - r->updatedn_group_check_interval = atoi(val); - slapi_ch_free((void **)&val); + if ((val = slapi_entry_attr_get_charptr(e, attr_replicaBindDnGroupCheckInterval))) { + if (repl_config_valid_num(attr_replicaBindDnGroupCheckInterval, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { + slapi_ch_free_string(&val); + return -1; + } + r->updatedn_group_check_interval = interval; + slapi_ch_free_string(&val); } else { r->updatedn_group_check_interval = -1; } @@ -2041,18 +2077,26 @@ _replica_init_from_config(Replica *r, Slapi_Entry *e, char *errortext) * since we don't know about LCUP replicas, and they can just * turn up whenever they want to. */ - if (slapi_entry_attr_find(e, type_replicaPurgeDelay, &a) == -1) { - /* No purge delay provided, so use default */ - r->repl_purge_delay = 60 * 60 * 24 * 7; /* One week, in seconds */ + if ((val = slapi_entry_attr_get_charptr(e, type_replicaPurgeDelay))) { + if (repl_config_valid_num(type_replicaPurgeDelay, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { + slapi_ch_free_string(&val); + return -1; + } + r->repl_purge_delay = interval; + slapi_ch_free_string(&val); } else { - r->repl_purge_delay = slapi_entry_attr_get_uint(e, type_replicaPurgeDelay); + r->repl_purge_delay = 60 * 60 * 24 * 7; /* One week, in seconds */ } - if (slapi_entry_attr_find(e, type_replicaTombstonePurgeInterval, &a) == -1) { - /* No reap interval provided, so use default */ - r->tombstone_reap_interval = 3600 * 24; /* One day */ + if ((val = slapi_entry_attr_get_charptr(e, type_replicaTombstonePurgeInterval))) { + if (repl_config_valid_num(type_replicaTombstonePurgeInterval, val, -1, INT_MAX, &rc, errormsg, &interval) != 0) { + slapi_ch_free_string(&val); + return -1; + } + r->tombstone_reap_interval = interval; + slapi_ch_free_string(&val); } else { - r->tombstone_reap_interval = slapi_entry_attr_get_int(e, type_replicaTombstonePurgeInterval); + r->tombstone_reap_interval = 3600 * 24; /* One week, in seconds */ } r->tombstone_reap_stop = r->tombstone_reap_active = PR_FALSE; @@ -3534,7 +3578,7 @@ replica_log_ruv_elements_nolock(const Replica *r) } void -replica_set_purge_delay(Replica *r, PRUint32 purge_delay) +replica_set_purge_delay(Replica *r, uint32_t purge_delay) { PR_ASSERT(r); replica_lock(r->repl_lock); @@ -3710,7 +3754,7 @@ replica_set_ruv_dirty(Replica *r) } PRBool -replica_is_state_flag_set(Replica *r, PRInt32 flag) +replica_is_state_flag_set(Replica *r, int32_t flag) { PR_ASSERT(r); if (r) @@ -3720,7 +3764,7 @@ replica_is_state_flag_set(Replica *r, PRInt32 flag) } void -replica_set_state_flag(Replica *r, PRUint32 flag, PRBool clear) +replica_set_state_flag(Replica *r, uint32_t flag, PRBool clear) { if (r == NULL) return; @@ -3994,7 +4038,7 @@ replica_get_attr(Slapi_PBlock *pb, const char *type, void *value) return rc; } -PRUint64 +uint64_t replica_get_backoff_min(Replica *r) { if (r) { @@ -4004,7 +4048,7 @@ replica_get_backoff_min(Replica *r) } } -PRUint64 +uint64_t replica_get_backoff_max(Replica *r) { if (r) { @@ -4015,7 +4059,7 @@ replica_get_backoff_max(Replica *r) } void -replica_set_backoff_min(Replica *r, PRUint64 min) +replica_set_backoff_min(Replica *r, uint64_t min) { if (r) { slapi_counter_set_value(r->backoff_min, min); @@ -4023,7 +4067,7 @@ replica_set_backoff_min(Replica *r, PRUint64 min) } void -replica_set_backoff_max(Replica *r, PRUint64 max) +replica_set_backoff_max(Replica *r, uint64_t max) { if (r) { slapi_counter_set_value(r->backoff_max, max); @@ -4031,14 +4075,14 @@ replica_set_backoff_max(Replica *r, PRUint64 max) } void -replica_set_precise_purging(Replica *r, PRUint64 on_off) +replica_set_precise_purging(Replica *r, uint64_t on_off) { if (r) { slapi_counter_set_value(r->precise_purging, on_off); } } -PRUint64 +uint64_t replica_get_precise_purging(Replica *r) { if (r) { diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index 7477a292c..9c3c75458 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -405,28 +405,35 @@ replica_config_modify(Slapi_PBlock *pb, } else if (strcasecmp(config_attr, attr_replicaBindDnGroup) == 0) { *returncode = replica_config_change_updatedngroup(r, mods[i], errortext, apply_mods); } else if (strcasecmp(config_attr, attr_replicaBindDnGroupCheckInterval) == 0) { - int interval = atoi(config_attr_value); - replica_set_groupdn_checkinterval(r, interval); + int64_t interval = 0; + if (repl_config_valid_num(config_attr, config_attr_value, -1, INT_MAX, returncode, errortext, &interval) == 0) { + replica_set_groupdn_checkinterval(r, interval); + } else { + break; + } } else if (strcasecmp(config_attr, attr_replicaType) == 0) { + int64_t rtype; slapi_ch_free_string(&new_repl_type); - new_repl_type = slapi_ch_strdup(config_attr_value); + if (repl_config_valid_num(config_attr, config_attr_value, 1, 3, returncode, errortext, &rtype) == 0) { + new_repl_type = slapi_ch_strdup(config_attr_value); + } else { + break; + } } else if (strcasecmp(config_attr, attr_replicaId) == 0) { - char *endp = NULL; int64_t rid = 0; - errno = 0; - rid = strtoll(config_attr_value, &endp, 10); - if (*endp != '\0' || rid > 65535 || rid < 1 || errno == ERANGE) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number between 1 and 65535.\n", - config_attr, config_attr_value); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + if (repl_config_valid_num(config_attr, config_attr_value, 1, 65535, returncode, errortext, &rid) == 0) { + slapi_ch_free_string(&new_repl_id); + new_repl_id = slapi_ch_strdup(config_attr_value); + } else { break; } - slapi_ch_free_string(&new_repl_id); - new_repl_id = slapi_ch_strdup(config_attr_value); } else if (strcasecmp(config_attr, attr_flags) == 0) { - *returncode = replica_config_change_flags(r, config_attr_value, errortext, apply_mods); + int64_t rflags = 0; + if (repl_config_valid_num(config_attr, config_attr_value, 0, 1, returncode, errortext, &rflags) == 0) { + *returncode = replica_config_change_flags(r, config_attr_value, errortext, apply_mods); + } else { + break; + } } else if (strcasecmp(config_attr, TASK_ATTR) == 0) { *returncode = replica_execute_task(mtnode_ext->replica, config_attr_value, errortext, apply_mods); } else if (strcasecmp(config_attr, attr_replicaReferral) == 0) { @@ -442,18 +449,21 @@ replica_config_modify(Slapi_PBlock *pb, } } else if (strcasecmp(config_attr, type_replicaPurgeDelay) == 0) { if (apply_mods && config_attr_value[0]) { - PRUint32 delay; - if (isdigit(config_attr_value[0])) { - delay = (unsigned int)atoi(config_attr_value); + int64_t delay = 0; + if (repl_config_valid_num(config_attr, config_attr_value, -1, INT_MAX, returncode, errortext, &delay) == 0) { replica_set_purge_delay(r, delay); - } else - *returncode = LDAP_OPERATIONS_ERROR; + } else { + break; + } } } else if (strcasecmp(config_attr, type_replicaTombstonePurgeInterval) == 0) { if (apply_mods && config_attr_value[0]) { - long interval; - interval = atol(config_attr_value); - replica_set_tombstone_reap_interval(r, interval); + int64_t interval; + if (repl_config_valid_num(config_attr, config_attr_value, -1, INT_MAX, returncode, errortext, &interval) == 0) { + replica_set_tombstone_reap_interval(r, interval); + } else { + break; + } } } /* ignore modifiers attributes added by the server */ @@ -461,73 +471,55 @@ replica_config_modify(Slapi_PBlock *pb, *returncode = LDAP_SUCCESS; } else if (strcasecmp(config_attr, type_replicaProtocolTimeout) == 0) { if (apply_mods) { - PRUint64 ptimeout = 0; - - ptimeout = atoll(config_attr_value); - - if (ptimeout <= 0) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number greater than zero.\n", - config_attr, config_attr_value); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + int64_t ptimeout = 0; + if (repl_config_valid_num(config_attr, config_attr_value, 1, INT_MAX, returncode, errortext, &ptimeout) == 0) { + replica_set_protocol_timeout(r, ptimeout); + } else { break; } - replica_set_protocol_timeout(r, ptimeout); } } else if (strcasecmp(config_attr, type_replicaBackoffMin) == 0) { if (apply_mods) { - uint64_t val = atoll(config_attr_value); - uint64_t max; - - if (val <= 0) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number greater than zero.\n", - config_attr, config_attr_value); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); - break; - } - max = replica_get_backoff_max(r); - if (val > max){ - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number less than the max backoff time (%d).\n", - config_attr, config_attr_value, (int)max); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + int64_t val = 0; + int64_t max; + if (repl_config_valid_num(config_attr, config_attr_value, 1, INT_MAX, returncode, errortext, &val) == 0) { + max = replica_get_backoff_max(r); + if (val > max){ + *returncode = LDAP_UNWILLING_TO_PERFORM; + PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, + "Attribute %s value (%s) is invalid, must be a number less than the max backoff time (%d).\n", + config_attr, config_attr_value, (int)max); + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + break; + } + replica_set_backoff_min(r, val); + } else { break; } - replica_set_backoff_min(r, val); } } else if (strcasecmp(config_attr, type_replicaBackoffMax) == 0) { if (apply_mods) { - uint64_t val = atoll(config_attr_value); - uint64_t min; - - if (val <= 0) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number greater than zero.\n", - config_attr, config_attr_value); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", - errortext); - break; - } - min = replica_get_backoff_min(r); - if (val < min) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number more than the min backoff time (%d).\n", - config_attr, config_attr_value, (int)min); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + int64_t val = 0; + int64_t min; + if (repl_config_valid_num(config_attr, config_attr_value, 1, INT_MAX, returncode, errortext, &val) == 0) { + min = replica_get_backoff_min(r); + if (val < min) { + *returncode = LDAP_UNWILLING_TO_PERFORM; + PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, + "Attribute %s value (%s) is invalid, must be a number more than the min backoff time (%d).\n", + config_attr, config_attr_value, (int)min); + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "replica_config_modify - %s\n", errortext); + break; + } + replica_set_backoff_max(r, val); + } else { break; } - replica_set_backoff_max(r, val); } } else if (strcasecmp(config_attr, type_replicaPrecisePurge) == 0) { if (apply_mods) { if (config_attr_value[0]) { - PRUint64 on_off = 0; + uint64_t on_off = 0; if (strcasecmp(config_attr_value, "on") == 0) { on_off = 1; @@ -550,19 +542,11 @@ replica_config_modify(Slapi_PBlock *pb, } } else if (strcasecmp(config_attr, type_replicaReleaseTimeout) == 0) { if (apply_mods) { - long val = atol(config_attr_value); - - if (val < 0) { - *returncode = LDAP_UNWILLING_TO_PERFORM; - PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, - "Attribute %s value (%s) is invalid, must be a number zero or greater.\n", - config_attr, config_attr_value); - slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, - "replica_config_modify - %s\n", errortext); - break; - } else { - /* Set the timeout */ + int64_t val; + if (repl_config_valid_num(config_attr, config_attr_value, 1, INT_MAX, returncode, errortext, &val) == 0) { replica_set_release_timeout(r, val); + } else { + break; } } } else { @@ -1011,7 +995,7 @@ replica_config_change_flags(Replica *r, const char *new_flags, char *returntext PR_ASSERT(r); if (apply_mods) { - PRUint32 flags; + uint32_t flags; flags = atol(new_flags); diff --git a/ldap/servers/plugins/replication/replutil.c b/ldap/servers/plugins/replication/replutil.c index 1b0446788..7cc132362 100644 --- a/ldap/servers/plugins/replication/replutil.c +++ b/ldap/servers/plugins/replication/replutil.c @@ -1061,3 +1061,29 @@ repl_set_repl_plugin_path(const char *path) { replpluginpath = slapi_ch_strdup(path); } + +int +repl_config_valid_num(const char *config_attr, char *config_attr_value, int64_t min, int64_t max, + int *returncode, char *errortext, int64_t *retval) +{ + int rc = 0; + char *endp = NULL; + int64_t val; + errno = 0; + + val = strtol(config_attr_value, &endp, 10); + if (*endp != '\0' || val < min || val > max || errno == ERANGE) { + *returncode = LDAP_UNWILLING_TO_PERFORM; + if (errortext){ + PR_snprintf(errortext, SLAPI_DSE_RETURNTEXT_SIZE, + "Attribute %s value (%s) is invalid, must be a number between %ld and %ld.", + config_attr, config_attr_value, min, max); + slapi_log_err(SLAPI_LOG_ERR, repl_plugin_name, "repl_config_valid_num - %s\n", + errortext); + } + rc = -1; + } else { + *retval = val; + } + return rc; +}
0
194e1db6c9f94253fc4943fb08eb40cc848d1c94
389ds/389-ds-base
Reliability improvements to DS allocate functions Signed-off-by: Mark Reynolds <[email protected]>
commit 194e1db6c9f94253fc4943fb08eb40cc848d1c94 Author: William Brown <[email protected]> Date: Thu Aug 20 14:26:15 2015 +0930 Reliability improvements to DS allocate functions Signed-off-by: Mark Reynolds <[email protected]> diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 246dd69b6..60b041986 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -455,7 +455,8 @@ class DirSrv(SimpleLDAPObject): self.serverid = args.get(SER_SERVERID_PROP, None) self.groupid = args.get(SER_GROUP_ID, self.userid) self.backupdir = args.get(SER_BACKUP_INST_DIR, DEFAULT_BACKUPDIR) - self.prefix = args.get(SER_DEPLOYED_DIR) + # Allocate from the args, or use our env, or use / + self.prefix = args.get(SER_DEPLOYED_DIR, self.prefix ) # Those variables needs to be revisited (sroot for 64 bits) #self.sroot = os.path.join(self.prefix, "lib/dirsrv") @@ -764,7 +765,9 @@ class DirSrv(SimpleLDAPObject): SER_DEPLOYED_DIR: self.prefix, SER_BACKUP_INST_DIR: self.backupdir} content = formatInfData(args) - DirSrvTools.runInfProg(prog, content, verbose, prefix=self.prefix) + result = DirSrvTools.runInfProg(prog, content, verbose, prefix=self.prefix) + if result != 0: + raise Exception('Failed to run setup-ds.pl') def create(self): """ diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index d681172ed..3e8474501 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -556,8 +556,8 @@ class DirSrvTools(object): print "timed out waiting to read from", cmd child_stdout.close() exitCode = pipe.wait() - if verbose: - print "%s returned exit code %s" % (prog, exitCode) + #if verbose: + log.debug("%s returned exit code %s" % (prog, exitCode)) return exitCode @staticmethod
0
98d6c7f8afd4dd8cc802c3b3c7e6bb133c8c09c9
389ds/389-ds-base
Issue 49481 - remove unused or unnecessary database plugin functions Description: Removed some unused database plugin initializations. Also cleaned up some of the logging in the bdb specific code that was not using the correct function name. Fixes: https://pagure.io/389-ds-base/issue/49481 Reviewed by: elkris, tbordaz, and firstyear (Thanks!!!)
commit 98d6c7f8afd4dd8cc802c3b3c7e6bb133c8c09c9 Author: Mark Reynolds <[email protected]> Date: Fri Jul 24 14:11:00 2020 -0400 Issue 49481 - remove unused or unnecessary database plugin functions Description: Removed some unused database plugin initializations. Also cleaned up some of the logging in the bdb specific code that was not using the correct function name. Fixes: https://pagure.io/389-ds-base/issue/49481 Reviewed by: elkris, tbordaz, and firstyear (Thanks!!!) diff --git a/Makefile.am b/Makefile.am index 4ea239ad5..2e42695ab 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1766,7 +1766,6 @@ libchainingdb_plugin_la_SOURCES = ldap/servers/plugins/chainingdb/cb_abandon.c \ ldap/servers/plugins/chainingdb/cb_monitor.c \ ldap/servers/plugins/chainingdb/cb_schema.c \ ldap/servers/plugins/chainingdb/cb_search.c \ - ldap/servers/plugins/chainingdb/cb_size.c \ ldap/servers/plugins/chainingdb/cb_start.c \ ldap/servers/plugins/chainingdb/cb_temp.c \ ldap/servers/plugins/chainingdb/cb_test.c \ diff --git a/ldap/schema/01core389.ldif b/ldap/schema/01core389.ldif index d1063a491..8db58de07 100644 --- a/ldap/schema/01core389.ldif +++ b/ldap/schema/01core389.ldif @@ -318,6 +318,10 @@ attributeTypes: ( 2.16.840.1.113730.3.1.2367 NAME 'nsslapd-libPath' DESC 'Rewrit attributeTypes: ( 2.16.840.1.113730.3.1.2368 NAME 'nsslapd-filterrewriter' DESC 'Filter rewriter function name' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN '389 Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2369 NAME 'nsslapd-returnedAttrRewriter' DESC 'Returned attribute rewriter function name' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN '389 Directory Server' ) attributeTypes: ( 2.16.840.1.113730.3.1.2370 NAME 'nsslapd-enable-upgrade-hash' DESC 'Upgrade password hash on bind' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN '389 Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.602 NAME 'entrydn' DESC 'Internal database attribute for the entry DN' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.603 NAME 'dncomp' DESC 'Internal database attribute for each DN component' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.604 NAME 'parentid' DESC 'Internal database attribute for the parent ID of the entry' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN 'Netscape Directory Server' ) +attributeTypes: ( 2.16.840.1.113730.3.1.605 NAME 'entryid' DESC 'Internal database attribute for the ID of the entry' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation X-ORIGIN 'Netscape Directory Server' ) # # objectclasses # diff --git a/ldap/servers/plugins/chainingdb/cb.h b/ldap/servers/plugins/chainingdb/cb.h index 9af6dab64..fc4c3ee9c 100644 --- a/ldap/servers/plugins/chainingdb/cb.h +++ b/ldap/servers/plugins/chainingdb/cb.h @@ -448,7 +448,6 @@ int chainingdb_next_search_entry(Slapi_PBlock *pb); int chainingdb_build_candidate_list(Slapi_PBlock *pb); int chainingdb_start(Slapi_PBlock *pb); int chainingdb_bind(Slapi_PBlock *pb); -int cb_db_size(Slapi_PBlock *pb); int cb_back_close(Slapi_PBlock *pb); int cb_back_cleanup(Slapi_PBlock *pb); void chaining_back_search_results_release(void **sr); diff --git a/ldap/servers/plugins/chainingdb/cb_init.c b/ldap/servers/plugins/chainingdb/cb_init.c index 28b97e9d6..cd0e84e87 100644 --- a/ldap/servers/plugins/chainingdb/cb_init.c +++ b/ldap/servers/plugins/chainingdb/cb_init.c @@ -87,8 +87,6 @@ chaining_back_init(Slapi_PBlock *pb) (void *)chaining_back_modrdn); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_ABANDON_FN, (void *)chaining_back_abandon); - rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_SIZE_FN, - (void *)cb_db_size); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_CLOSE_FN, (void *)cb_back_close); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_CLEANUP_FN, @@ -97,8 +95,6 @@ chaining_back_init(Slapi_PBlock *pb) /**** rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_ENTRY_RELEASE_FN, (void *) chaining_back_entry_release ); - rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_INIT_INSTANCE_FN, - (void *) chaining_back_init); rc |= slapi_pblock_set( pb, SLAPI_PLUGIN_DB_TEST_FN, (void *) cb_back_test ); ****/ diff --git a/ldap/servers/plugins/chainingdb/cb_size.c b/ldap/servers/plugins/chainingdb/cb_size.c deleted file mode 100644 index 39e530e75..000000000 --- a/ldap/servers/plugins/chainingdb/cb_size.c +++ /dev/null @@ -1,29 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * - * License: GPL (version 3 or any later version). - * See LICENSE for details. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -#include <config.h> -#endif - -#include "cb.h" - -int -cb_db_size(Slapi_PBlock *pb) -{ - - /* - ** Return the size in byte of the local database storage - ** Size is 0 for a chaining backend - */ - - unsigned int size = 0; - - slapi_pblock_set(pb, SLAPI_DBSIZE, &size); - return 0; -} diff --git a/ldap/servers/slapd/back-ldbm/archive.c b/ldap/servers/slapd/back-ldbm/archive.c index 6047e789c..177c3f3c4 100644 --- a/ldap/servers/slapd/back-ldbm/archive.c +++ b/ldap/servers/slapd/back-ldbm/archive.c @@ -68,7 +68,7 @@ ldbm_back_archive2ldbm(Slapi_PBlock *pb) mapping_tree_init(); if (dblayer_setup(li)) { - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_init", "dblayer_setup failed\n"); + slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_archive2ldbm", "dblayer_setup failed\n"); return -1; } @@ -283,7 +283,7 @@ ldbm_back_ldbm2archive(Slapi_PBlock *pb) /* copied here, need better solution */ /* initialize dblayer */ if (dblayer_setup(li)) { - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_init", "dblayer_setup failed\n"); + slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_ldbm2archive", "dblayer_setup failed\n"); goto out; } diff --git a/ldap/servers/slapd/back-ldbm/back-ldbm.h b/ldap/servers/slapd/back-ldbm/back-ldbm.h index e325d2518..2636d4d0f 100644 --- a/ldap/servers/slapd/back-ldbm/back-ldbm.h +++ b/ldap/servers/slapd/back-ldbm/back-ldbm.h @@ -802,14 +802,6 @@ typedef struct _back_search_result_set /* Name of attribute type used for binder-based look through simple paged limit */ #define LDBM_PAGEDALLIDSLIMIT_AT "nsPagedIDListScanLimit" -/* OIDs for attribute types used internally */ -#define LDBM_ENTRYDN_OID "2.16.840.1.113730.3.1.602" -#define LDBM_DNCOMP_OID "2.16.840.1.113730.3.1.603" -#define LDBM_PARENTID_OID "2.16.840.1.113730.3.1.604" -#define LDBM_ENTRYID_OID "2.16.840.1.113730.3.1.605" -#define LDBM_ENTRYUSN_OID "2.16.840.1.113730.3.1.2096" -/* #define LDBM_ENTRYRDN_OID "2.16.840.1.113730.3.1.2097" */ - #define LDBM_ANCESTORID_STR "ancestorid" #define LDBM_ENTRYDN_STR SLAPI_ATTR_ENTRYDN #define LDBM_ENTRYRDN_STR "entryrdn" diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_ldif2db.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_ldif2db.c index 506c285a3..84dfb7d9f 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_ldif2db.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_ldif2db.c @@ -2235,7 +2235,7 @@ ldbm_exclude_attr_from_export(struct ldbminfo *li, const char *attr, int dump_un } /* - * ldbm_back_upgradedb - + * bdb_upgradedb - * * functions to convert idl from the old format to the new one * (604921) Support a database uprev process any time post-install @@ -2246,7 +2246,7 @@ int upgradedb_copy_logfiles(struct ldbminfo *li, char *destination_dir, int rest int upgradedb_delete_indices_4cmd(ldbm_instance *inst, int flags); /* - * ldbm_back_upgradedb - + * bdb_upgradedb - * check the DB version and if it's old idl'ed index, * then reindex using new idl. * @@ -2279,7 +2279,7 @@ bdb_upgradedb(Slapi_PBlock *pb) PRUint32 dbversion_flags = DBVERSION_ALL; slapi_pblock_get(pb, SLAPI_SEQ_TYPE, &up_flags); - slapi_log_err(SLAPI_LOG_TRACE, "ldbm_back_upgradedb", "Reindexing all...\n"); + slapi_log_err(SLAPI_LOG_TRACE, "bdb_upgradedb", "Reindexing all...\n"); slapi_pblock_get(pb, SLAPI_TASK_FLAGS, &task_flags); slapi_pblock_get(pb, SLAPI_BACKEND_TASK, &task); slapi_pblock_get(pb, SLAPI_DB2LDIF_SERVER_RUNNING, &server_running); @@ -2296,7 +2296,7 @@ bdb_upgradedb(Slapi_PBlock *pb) ldbm_instance *inst = NULL; /* server is up -- mark all backends busy */ - slapi_log_err(SLAPI_LOG_TRACE, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_TRACE, "bdb_upgradedb", "server is up -- marking all LDBM backends busy\n"); for (inst_obj = objset_first_obj(li->li_instance_set); inst_obj; inst_obj = objset_next_obj(li->li_instance_set, inst_obj)) { @@ -2305,7 +2305,7 @@ bdb_upgradedb(Slapi_PBlock *pb) /* BUSY flag is cleared at the end of import_main (join thread); it should not cleared in this thread [610347] */ if (instance_set_busy(inst) != 0) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "ldbm: '%s' is already in the middle of " "another task and cannot be disturbed.\n", inst->inst_name); @@ -2334,7 +2334,7 @@ bdb_upgradedb(Slapi_PBlock *pb) * DN2RDN option (-r) is given, but subtree-rename is off. * Print an error and back off. */ - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "DN2RDN option (-r) is given, but %s is off in " "dse.ldif. Please change the value to on.\n", CONFIG_ENTRYRDN_SWITCH); @@ -2359,14 +2359,14 @@ bdb_upgradedb(Slapi_PBlock *pb) need_upgrade = (rval & (DBVERSION_UPGRADE_3_4 | DBVERSION_UPGRADE_4_4)); } if (!need_upgrade) { - slapi_log_err(SLAPI_LOG_INFO, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_INFO, "bdb_upgradedb", "Index version is up-to-date\n"); return 0; } } } else { slapi_log_err(SLAPI_LOG_WARNING, - "ldbm_back_upgradedb", "No instance to be upgraded\n"); + "bdb_upgradedb", "No instance to be upgraded\n"); return -1; } @@ -2413,7 +2413,7 @@ bdb_upgradedb(Slapi_PBlock *pb) since dblayer_close is called in upgradedb_core => bdb_back_ldif2db */ if (0 != bdb_start(li, DBLAYER_IMPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "Failed to init database\n"); goto fail1; } @@ -2432,7 +2432,7 @@ bdb_upgradedb(Slapi_PBlock *pb) if (inst_dirp != inst_dir) slapi_ch_free_string(&inst_dirp); if (backup_rval < 0) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "Failed to backup index files (instance %s).\n", inst_dirp); goto fail1; } @@ -2442,7 +2442,7 @@ bdb_upgradedb(Slapi_PBlock *pb) rval = upgradedb_delete_indices_4cmd(inst, up_flags); if (rval) { upgrade_rval += rval; - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_WARNING, "bdb_upgradedb", "Can't clean up indices in %s\n", inst->inst_dir_name); continue; /* Need to make all backups; continue */ } @@ -2450,7 +2450,7 @@ bdb_upgradedb(Slapi_PBlock *pb) rval = dblayer_delete_indices(inst); if (rval) { upgrade_rval += rval; - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_WARNING, "bdb_upgradedb", "Can't clean up indices in %s\n", inst->inst_dir_name); continue; /* Need to make all backups; continue */ } @@ -2459,7 +2459,7 @@ bdb_upgradedb(Slapi_PBlock *pb) rval = upgradedb_core(pb, inst); if (rval) { upgrade_rval += rval; - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "upgradedb: Failed to upgrade database %s\n", inst->inst_name); if (run_from_cmdline) { @@ -2508,7 +2508,7 @@ bdb_upgradedb(Slapi_PBlock *pb) /* close the database down again */ if (run_from_cmdline) { if (0 != dblayer_close(li, DBLAYER_IMPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "Failed to close database\n"); goto fail1; } @@ -2532,7 +2532,7 @@ fail1: * We just want not to generate a guardian file... */ if (0 != dblayer_close(li, DBLAYER_ARCHIVE_MODE)) - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradedb", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradedb", "Failed to close database\n"); /* restore from the backup, if possible */ @@ -3150,7 +3150,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) return -1; } } else { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", " Online mode is not supported. " "Shutdown the server and run the tool\n"); goto bail; @@ -3159,11 +3159,11 @@ bdb_upgradednformat(Slapi_PBlock *pb) /* Find the instance that the ldif2db will be done on. */ inst = ldbm_instance_find_by_name(li, instance_name); if (NULL == inst) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Unknown ldbm instance %s\n", instance_name); goto bail; } - slapi_log_err(SLAPI_LOG_INFO, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_INFO, "bdb_upgradednformat", "%s: Start upgrade dn format.\n", inst->inst_name); slapi_pblock_set(pb, SLAPI_BACKEND, inst->inst_be); @@ -3172,14 +3172,14 @@ bdb_upgradednformat(Slapi_PBlock *pb) prst = PR_GetFileInfo64(rawworkdbdir, &prfinfo); if (PR_FAILURE == prst || PR_FILE_DIRECTORY != prfinfo.type) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Working DB instance dir %s is not a directory\n", rawworkdbdir); goto bail; } dirhandle = PR_OpenDir(rawworkdbdir); if (!dirhandle) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Failed to open working DB instance dir %s\n", rawworkdbdir); goto bail; @@ -3196,7 +3196,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) PR_CloseDir(dirhandle); if (!found) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Working DB instance dir %s does not include %s file\n", rawworkdbdir, ID2ENTRY); goto bail; @@ -3231,7 +3231,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) rc = 3; /* 0: need upgrade (dn norm sp, only) */ } else { /* DN format already takes care of the multiple spaces */ - slapi_log_err(SLAPI_LOG_INFO, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_INFO, "bdb_upgradednformat", "Instance %s in %s is up-to-date\n", instance_name, workdbdir); rc = 0; /* 0: up-to-date */ @@ -3244,7 +3244,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) rc = 1; /* 0: need upgrade (both) */ } } else { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Failed to get DBVERSION (Instance name: %s, dir %s)\n", instance_name, workdbdir); rc = -1; /* error */ @@ -3253,7 +3253,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) sep = PL_strrchr(workdbdir, '/'); if (!sep) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Working DB instance dir %s does not include %s file\n", workdbdir, ID2ENTRY); goto bail; @@ -3265,7 +3265,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) if (run_from_cmdline) { if (0 != bdb_start(li, DBLAYER_IMPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Failed to init database\n"); goto bail; } @@ -3274,7 +3274,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) /* bdb_instance_start will init the id2entry index. */ be = inst->inst_be; if (0 != bdb_instance_start(be, DBLAYER_IMPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Failed to init instance %s\n", inst->inst_name); goto bail; } @@ -3288,7 +3288,7 @@ bdb_upgradednformat(Slapi_PBlock *pb) /* close the database */ if (run_from_cmdline) { if (0 != dblayer_close(li, DBLAYER_IMPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_upgradednformat", + slapi_log_err(SLAPI_LOG_ERR, "bdb_upgradednformat", "Failed to close database\n"); goto bail; } diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_misc.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_misc.c index 340e4a57e..5ad6006e9 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_misc.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_misc.c @@ -220,16 +220,16 @@ bdb_start_autotune(struct ldbminfo *li) /* Check the values are sane. */ if ((autosize_percentage > 100) || (import_percentage > 100) || (autosize_db_percentage_split > 100) || ((autosize_percentage > 0) && (import_percentage > 0) && (autosize_percentage + import_percentage > 100))) { - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_start", "Cache autosizing: bad settings, value or sum of values can not larger than 100.\n"); - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_start", "You should change nsslapd-cache-autosize + nsslapd-import-cache-autosize in dse.ldif to be less than 100.\n"); - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_start", "Reasonable starting values are nsslapd-cache-autosize: 10, nsslapd-import-cache-autosize: -1.\n"); + slapi_log_err(SLAPI_LOG_CRIT, "bdb_start_autotune", "Cache autosizing: bad settings, value or sum of values can not larger than 100.\n"); + slapi_log_err(SLAPI_LOG_CRIT, "bdb_start_autotune", "You should change nsslapd-cache-autosize + nsslapd-import-cache-autosize in dse.ldif to be less than 100.\n"); + slapi_log_err(SLAPI_LOG_CRIT, "bdb_start_autotune", "Reasonable starting values are nsslapd-cache-autosize: 10, nsslapd-import-cache-autosize: -1.\n"); return SLAPI_FAIL_GENERAL; } /* Get our platform memory values. */ slapi_pal_meminfo *mi = spal_meminfo_get(); if (mi == NULL) { - slapi_log_err(SLAPI_LOG_CRIT, "ldbm_back_start", "Unable to determine system page limits\n"); + slapi_log_err(SLAPI_LOG_CRIT, "bdb_start_autotune", "Unable to determine system page limits\n"); return SLAPI_FAIL_GENERAL; } @@ -239,8 +239,8 @@ bdb_start_autotune(struct ldbminfo *li) /* In the case it is not, this will *reduce* the allocation */ issane = util_is_cachesize_sane(mi, &zone_size); if (issane == UTIL_CACHESIZE_REDUCED) { - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "Your autosized cache values have been reduced. Likely your nsslapd-cache-autosize percentage is too high.\n"); - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "%s", msg); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "Your autosized cache values have been reduced. Likely your nsslapd-cache-autosize percentage is too high.\n"); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "%s", msg); } /* It's valid, lets divide it up and set according to user prefs */ db_size = (autosize_db_percentage_split * zone_size) / 100; @@ -288,8 +288,8 @@ bdb_start_autotune(struct ldbminfo *li) } } - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "found %" PRIu64 "k physical memory\n", mi->system_total_bytes / 1024); - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "found %" PRIu64 "k available\n", mi->system_available_bytes / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "found %" PRIu64 "k physical memory\n", mi->system_total_bytes / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "found %" PRIu64 "k available\n", mi->system_available_bytes / 1024); /* We've now calculated the autotuning values. Do we need to apply it? * we use the logic of "if size is 0, or autosize is > 0. This way three @@ -304,7 +304,7 @@ bdb_start_autotune(struct ldbminfo *li) /* First, check the dbcache */ if (li->li_dbcachesize == 0 || li->li_cache_autosize > 0) { - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "cache autosizing: db cache: %" PRIu64 "k\n", db_size / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "cache autosizing: db cache: %" PRIu64 "k\n", db_size / 1024); if (db_size < (500 * MEGABYTE)) { db_size = db_size / 1.25; } @@ -334,12 +334,12 @@ bdb_start_autotune(struct ldbminfo *li) * it's highly unlikely. */ if (cache_size == 0 || cache_size == MINCACHESIZE || li->li_cache_autosize > 0) { - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "cache autosizing: %s entry cache (%" PRIu64 " total): %" PRIu64 "k\n", inst->inst_name, backend_count, entry_size / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "cache autosizing: %s entry cache (%" PRIu64 " total): %" PRIu64 "k\n", inst->inst_name, backend_count, entry_size / 1024); cache_set_max_entries(&(inst->inst_cache), -1); cache_set_max_size(&(inst->inst_cache), li->li_cache_autosize_ec, CACHE_TYPE_ENTRY); } if (dncache_size == 0 || dncache_size == MINCACHESIZE || li->li_cache_autosize > 0) { - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "cache autosizing: %s dn cache (%" PRIu64 " total): %" PRIu64 "k\n", inst->inst_name, backend_count, dn_size / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "cache autosizing: %s dn cache (%" PRIu64 " total): %" PRIu64 "k\n", inst->inst_name, backend_count, dn_size / 1024); cache_set_max_entries(&(inst->inst_dncache), -1); cache_set_max_size(&(inst->inst_dncache), li->li_dncache_autosize_ec, CACHE_TYPE_DN); } @@ -347,7 +347,7 @@ bdb_start_autotune(struct ldbminfo *li) cache_size = (PRUint64)cache_get_max_size(&(inst->inst_cache)); db_size = bdb_get_id2entry_size(inst); if (cache_size < db_size) { - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "%s: entry cache size %" PRIu64 " B is " "less than db size %" PRIu64 " B; " "We recommend to increase the entry cache size " @@ -363,26 +363,26 @@ bdb_start_autotune(struct ldbminfo *li) import_size = (import_percentage * mi->system_total_bytes) / 100; issane = util_is_cachesize_sane(mi, &import_size); if (issane == UTIL_CACHESIZE_REDUCED) { - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "Your autosized import cache values have been reduced. Likely your nsslapd-import-cache-autosize percentage is too high.\n"); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "Your autosized import cache values have been reduced. Likely your nsslapd-import-cache-autosize percentage is too high.\n"); } /* We just accept the reduced allocation here. */ - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "cache autosizing: import cache: %" PRIu64 "k\n", import_size / 1024); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "cache autosizing: import cache: %" PRIu64 "k\n", import_size / 1024); sprintf(size_to_str, "%" PRIu64, import_size); ldbm_config_internal_set(li, CONFIG_IMPORT_CACHESIZE, size_to_str); } /* Finally, lets check that the total result is sane. */ - slapi_log_err(SLAPI_LOG_NOTICE, "ldbm_back_start", "total cache size: %" PRIu64 " B; \n", total_cache_size); + slapi_log_err(SLAPI_LOG_NOTICE, "bdb_start_autotune", "total cache size: %" PRIu64 " B; \n", total_cache_size); issane = util_is_cachesize_sane(mi, &total_cache_size); if (issane != UTIL_CACHESIZE_VALID) { /* Right, it's time to panic */ - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "It is highly likely your memory configuration of all backends will EXCEED your systems memory.\n"); - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "In a future release this WILL prevent server start up. You MUST alter your configuration.\n"); - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "Total entry cache size: %" PRIu64 " B; dbcache size: %" PRIu64 " B; available memory size: %" PRIu64 " B; \n", + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "It is highly likely your memory configuration of all backends will EXCEED your systems memory.\n"); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "In a future release this WILL prevent server start up. You MUST alter your configuration.\n"); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "Total entry cache size: %" PRIu64 " B; dbcache size: %" PRIu64 " B; available memory size: %" PRIu64 " B; \n", total_cache_size, (uint64_t)li->li_dbcachesize, mi->system_available_bytes); - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_start", "%s\n", msg); + slapi_log_err(SLAPI_LOG_WARNING, "bdb_start_autotune", "%s\n", msg); /* WB 2016 - This should be UNCOMMENTED in a future release */ /* return SLAPI_FAIL_GENERAL; */ } diff --git a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_verify.c b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_verify.c index 42d1cd145..b93dcb95e 100644 --- a/ldap/servers/slapd/back-ldbm/db-bdb/bdb_verify.c +++ b/ldap/servers/slapd/back-ldbm/db-bdb/bdb_verify.c @@ -166,7 +166,7 @@ bdb_verify(Slapi_PBlock *pb) char **instance_names = NULL; char *dbdir = NULL; - slapi_log_err(SLAPI_LOG_TRACE, "ldbm_back_dbverify", "Verifying db files...\n"); + slapi_log_err(SLAPI_LOG_TRACE, "bdb_verify", "Verifying db files...\n"); slapi_pblock_get(pb, SLAPI_BACKEND_INSTANCE_NAME, &instance_names); slapi_pblock_get(pb, SLAPI_SEQ_TYPE, &verbose); slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &li); @@ -176,13 +176,12 @@ bdb_verify(Slapi_PBlock *pb) /* no write needed; choose EXPORT MODE */ if (0 != bdb_start(li, DBLAYER_EXPORT_MODE)) { - slapi_log_err(SLAPI_LOG_ERR, "ldbm_back_dbverify", - "dbverify: Failed to init database\n"); + slapi_log_err(SLAPI_LOG_ERR, "bdb_verify", "dbverify: Failed to init database\n"); return rval; } /* server is up */ - slapi_log_err(SLAPI_LOG_TRACE, "ldbm_back_dbverify", "server is up\n"); + slapi_log_err(SLAPI_LOG_TRACE, "bdb_verify", "server is up\n"); if (instance_names) /* instance is specified */ { char **inp = NULL; @@ -207,7 +206,7 @@ bdb_verify(Slapi_PBlock *pb) /* check if an import/restore is already ongoing... */ if (instance_set_busy(inst) != 0) { /* standalone, only. never happens */ - slapi_log_err(SLAPI_LOG_WARNING, "ldbm_back_dbverify", + slapi_log_err(SLAPI_LOG_WARNING, "bdb_verify", "Backend '%s' is already in the middle of " "another task and cannot be disturbed.\n", inst->inst_name); @@ -225,8 +224,7 @@ bdb_verify(Slapi_PBlock *pb) /* close the database down again */ rval = bdb_post_close(li, DBLAYER_EXPORT_MODE); if (0 != rval) { - slapi_log_err(SLAPI_LOG_ERR, - "ldbm_back_dbverify", "Failed to close database\n"); + slapi_log_err(SLAPI_LOG_ERR, "bdb_verify", "Failed to close database\n"); } return rval_main; diff --git a/ldap/servers/slapd/back-ldbm/init.c b/ldap/servers/slapd/back-ldbm/init.c index 4e38eb32b..3faa8ae19 100644 --- a/ldap/servers/slapd/back-ldbm/init.c +++ b/ldap/servers/slapd/back-ldbm/init.c @@ -19,30 +19,6 @@ static Slapi_PluginDesc pdesc = {"ldbm-backend", VENDOR, DS_PACKAGE_VERSION, "high-performance LDAP backend database plugin"}; -/* pb: not used */ -int -ldbm_back_add_schema(Slapi_PBlock *pb __attribute__((unused))) -{ - int rc = 0; - rc = slapi_add_internal_attr_syntax(LDBM_ENTRYDN_STR, - LDBM_ENTRYDN_OID, DN_SYNTAX_OID, DNMATCH_NAME, - SLAPI_ATTR_FLAG_SINGLE | SLAPI_ATTR_FLAG_NOUSERMOD); - - rc |= slapi_add_internal_attr_syntax("dncomp", - LDBM_DNCOMP_OID, DN_SYNTAX_OID, DNMATCH_NAME, - SLAPI_ATTR_FLAG_NOUSERMOD); - - rc |= slapi_add_internal_attr_syntax(LDBM_PARENTID_STR, - LDBM_PARENTID_OID, INTEGER_SYNTAX_OID, INTEGERMATCH_NAME, - SLAPI_ATTR_FLAG_SINGLE | SLAPI_ATTR_FLAG_NOUSERMOD); - - rc |= slapi_add_internal_attr_syntax("entryid", - LDBM_ENTRYID_OID, DIRSTRING_SYNTAX_OID, CASEIGNOREMATCH_NAME, - SLAPI_ATTR_FLAG_SINGLE | SLAPI_ATTR_FLAG_NOUSERMOD); - - return rc; -} - int ldbm_back_init(Slapi_PBlock *pb) { @@ -81,9 +57,6 @@ ldbm_back_init(Slapi_PBlock *pb) goto fail; } - /* add some private attributes */ - rc = ldbm_back_add_schema(pb); - /* set plugin private pointer and initialize locks, etc. */ rc = slapi_pblock_set(pb, SLAPI_PLUGIN_PRIVATE, (void *)li); @@ -158,15 +131,8 @@ ldbm_back_init(Slapi_PBlock *pb) (void *)dblayer_plugin_commit); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_ABORT_FN, (void *)dblayer_plugin_abort); - rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_SIZE_FN, - (void *)ldbm_db_size); - rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_INIT_INSTANCE_FN, - (void *)ldbm_back_init); /* register itself so that the secon instance - can be initialized */ rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_WIRE_IMPORT_FN, (void *)ldbm_back_wire_import); - rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_ADD_SCHEMA_FN, - (void *)ldbm_back_add_schema); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_GET_INFO_FN, (void *)ldbm_back_get_info); rc |= slapi_pblock_set(pb, SLAPI_PLUGIN_DB_SET_INFO_FN, diff --git a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c index f2ef5ecd4..257de55ad 100644 --- a/ldap/servers/slapd/back-ldbm/ldif2ldbm.c +++ b/ldap/servers/slapd/back-ldbm/ldif2ldbm.c @@ -328,7 +328,7 @@ ldbm_back_upgradedb(Slapi_PBlock *pb) } dblayer_private *priv = (dblayer_private *)li->li_dblayer_private; - return priv->dblayer_upgradedb_fn(pb);; + return priv->dblayer_upgradedb_fn(pb); } #define LOG "log." @@ -363,5 +363,5 @@ ldbm_back_upgradednformat(Slapi_PBlock *pb) slapi_pblock_get(pb, SLAPI_PLUGIN_PRIVATE, &li); dblayer_private *priv = (dblayer_private *)li->li_dblayer_private; - return priv->dblayer_upgradedn_fn(pb);; + return priv->dblayer_upgradedn_fn(pb); } diff --git a/ldap/servers/slapd/backend.c b/ldap/servers/slapd/backend.c index 78c00a5a8..10ad1622f 100644 --- a/ldap/servers/slapd/backend.c +++ b/ldap/servers/slapd/backend.c @@ -425,18 +425,12 @@ slapi_be_getentrypoint(Slapi_Backend *be, int entrypoint, void **ret_fnptr, Slap case SLAPI_PLUGIN_DB_PREV_SEARCH_RESULTS_FN: *ret_fnptr = be->be_prev_search_results; break; - case SLAPI_PLUGIN_DB_SIZE_FN: - *ret_fnptr = (void *)be->be_dbsize; - break; case SLAPI_PLUGIN_DB_TEST_FN: *ret_fnptr = (void *)be->be_dbtest; break; case SLAPI_PLUGIN_DB_RMDB_FN: *ret_fnptr = (void *)be->be_rmdb; break; - case SLAPI_PLUGIN_DB_INIT_INSTANCE_FN: - *ret_fnptr = (void *)be->be_init_instance; - break; case SLAPI_PLUGIN_DB_SEQ_FN: *ret_fnptr = (void *)be->be_seq; break; @@ -534,18 +528,12 @@ slapi_be_setentrypoint(Slapi_Backend *be, int entrypoint, void *ret_fnptr, Slapi case SLAPI_PLUGIN_DB_PREV_SEARCH_RESULTS_FN: be->be_prev_search_results = (VFP)ret_fnptr; break; - case SLAPI_PLUGIN_DB_SIZE_FN: - be->be_dbsize = (IFP)ret_fnptr; - break; case SLAPI_PLUGIN_DB_TEST_FN: be->be_dbtest = (IFP)ret_fnptr; break; case SLAPI_PLUGIN_DB_RMDB_FN: be->be_rmdb = (IFP)ret_fnptr; break; - case SLAPI_PLUGIN_DB_INIT_INSTANCE_FN: - be->be_init_instance = (IFP)ret_fnptr; - break; case SLAPI_PLUGIN_DB_SEQ_FN: be->be_seq = (IFP)ret_fnptr; break; diff --git a/ldap/servers/slapd/pblock.c b/ldap/servers/slapd/pblock.c index 3e369c6f8..2b6b4fd09 100644 --- a/ldap/servers/slapd/pblock.c +++ b/ldap/servers/slapd/pblock.c @@ -863,9 +863,6 @@ slapi_pblock_get(Slapi_PBlock *pblock, int arg, void *value) case SLAPI_PLUGIN_DB_WIRE_IMPORT_FN: (*(IFP *)value) = pblock->pb_plugin->plg_wire_import; break; - case SLAPI_PLUGIN_DB_ADD_SCHEMA_FN: - (*(IFP *)value) = pblock->pb_plugin->plg_add_schema; - break; case SLAPI_PLUGIN_DB_GET_INFO_FN: (*(IFP *)value) = pblock->pb_plugin->plg_get_info; break; @@ -899,12 +896,6 @@ slapi_pblock_get(Slapi_PBlock *pblock, int arg, void *value) } (*(IFP *)value) = pblock->pb_plugin->plg_rmdb; break; - case SLAPI_PLUGIN_DB_INIT_INSTANCE_FN: - if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { - return (-1); - } - (*(IFP *)value) = pblock->pb_plugin->plg_init_instance; - break; case SLAPI_PLUGIN_DB_LDIF2DB_FN: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { return (-1); @@ -971,12 +962,6 @@ slapi_pblock_get(Slapi_PBlock *pblock, int arg, void *value) } (*(IFP *)value) = pblock->pb_plugin->plg_un.plg_un_db.plg_un_db_abort; break; - case SLAPI_PLUGIN_DB_SIZE_FN: - if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { - return (-1); - } - (*(IFP *)value) = pblock->pb_plugin->plg_un.plg_un_db.plg_un_db_dbsize; - break; case SLAPI_PLUGIN_DB_TEST_FN: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { return (-1); @@ -2783,9 +2768,6 @@ slapi_pblock_set(Slapi_PBlock *pblock, int arg, void *value) case SLAPI_PLUGIN_DB_WIRE_IMPORT_FN: pblock->pb_plugin->plg_wire_import = (IFP)value; break; - case SLAPI_PLUGIN_DB_ADD_SCHEMA_FN: - pblock->pb_plugin->plg_add_schema = (IFP)value; - break; case SLAPI_PLUGIN_DB_GET_INFO_FN: pblock->pb_plugin->plg_get_info = (IFP)value; break; @@ -2816,13 +2798,6 @@ slapi_pblock_set(Slapi_PBlock *pblock, int arg, void *value) } pblock->pb_plugin->plg_rmdb = (IFP)value; break; - case SLAPI_PLUGIN_DB_INIT_INSTANCE_FN: - if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { - return (-1); - } - pblock->pb_plugin->plg_init_instance = (IFP)value; - break; - case SLAPI_PLUGIN_DB_LDIF2DB_FN: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { return (-1); @@ -2889,12 +2864,6 @@ slapi_pblock_set(Slapi_PBlock *pblock, int arg, void *value) } pblock->pb_plugin->plg_un.plg_un_db.plg_un_db_abort = (IFP)value; break; - case SLAPI_PLUGIN_DB_SIZE_FN: - if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { - return (-1); - } - pblock->pb_plugin->plg_un.plg_un_db.plg_un_db_dbsize = (IFP)value; - break; case SLAPI_PLUGIN_DB_TEST_FN: if (pblock->pb_plugin->plg_type != SLAPI_PLUGIN_DATABASE) { return (-1); diff --git a/ldap/servers/slapd/schema.c b/ldap/servers/slapd/schema.c index 0846444eb..c8ab33d59 100644 --- a/ldap/servers/slapd/schema.c +++ b/ldap/servers/slapd/schema.c @@ -4322,7 +4322,7 @@ init_schema_dse_ext(char *schemadir, Slapi_Backend *be, struct dse **local_psche /* borrow the task flag space */ slapi_pblock_set(pb, SLAPI_SCHEMA_FLAGS, (void *)&schema_flags); -/* add the objectclass attribute so we can do some basic schema + /* add the objectclass attribute so we can do some basic schema checking during initialization; this will be overridden when its "real" definition is read from the schema conf files */ @@ -4386,19 +4386,7 @@ init_schema_dse_ext(char *schemadir, Slapi_Backend *be, struct dse **local_psche be = be_new_internal(*local_pschemadse, "DSE", DSE_SCHEMA, &schema_plugin); be_addsuffix(be, &schema); } else { /* schema file reload */ - struct slapdplugin *backend_plugin = NULL; be_replace_dse_internal(be, *local_pschemadse); - - /* ldbm has some internal attributes to be added */ - backend_plugin = plugin_get_by_name("ldbm database"); - if (backend_plugin) { - if (backend_plugin->plg_add_schema) { - (backend_plugin->plg_add_schema)(NULL); - } else { - slapi_log_err(SLAPI_LOG_ERR, "init_schema_dse_ext", - "backend has not set internal schema\n"); - } - } } } } diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 79ef0b0b2..83f856bb5 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -909,16 +909,13 @@ int proxyauth_get_dn(Slapi_PBlock *pb, char **proxydnp, char **errtextp); #define SLAPI_PLUGIN_DB_DB2ARCHIVE_FN 223 #define SLAPI_PLUGIN_DB_NEXT_SEARCH_ENTRY_FN 224 #define SLAPI_PLUGIN_DB_FREE_RESULT_SET_FN 225 -#define SLAPI_PLUGIN_DB_SIZE_FN 226 #define SLAPI_PLUGIN_DB_TEST_FN 227 #define SLAPI_PLUGIN_DB_DB2INDEX_FN 228 #define SLAPI_PLUGIN_DB_NEXT_SEARCH_ENTRY_EXT_FN 229 #define SLAPI_PLUGIN_DB_ENTRY_RELEASE_FN 230 -#define SLAPI_PLUGIN_DB_INIT_INSTANCE_FN 231 #define SLAPI_PLUGIN_DB_WIRE_IMPORT_FN 234 #define SLAPI_PLUGIN_DB_UPGRADEDB_FN 235 #define SLAPI_PLUGIN_DB_DBVERIFY_FN 236 -#define SLAPI_PLUGIN_DB_ADD_SCHEMA_FN 237 #define SLAPI_PLUGIN_DB_SEARCH_RESULTS_RELEASE_FN 238 #define SLAPI_PLUGIN_DB_PREV_SEARCH_RESULTS_FN 239 #define SLAPI_PLUGIN_DB_UPGRADEDNFORMAT_FN 240
0
48b35ec4e48a38c257d5b9a5d2ef584661895261
389ds/389-ds-base
Trac Ticket #276 - Multiple threads simultaneously working on connection's private buffer causes ns-slapd to abort https://fedorahosted.org/389/ticket/276 Bug description: When a connection is to be released, the current code releases the connection object before making it readable, which leaves a small window for multiple threads accessing the same private buffer. Fix description: This patch moves the location of releasing the connection object after the connection is readable.
commit 48b35ec4e48a38c257d5b9a5d2ef584661895261 Author: Noriko Hosoi <[email protected]> Date: Sun Oct 14 16:46:16 2012 -0700 Trac Ticket #276 - Multiple threads simultaneously working on connection's private buffer causes ns-slapd to abort https://fedorahosted.org/389/ticket/276 Bug description: When a connection is to be released, the current code releases the connection object before making it readable, which leaves a small window for multiple threads accessing the same private buffer. Fix description: This patch moves the location of releasing the connection object after the connection is readable. diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index a3b1df52d..d598b0bb5 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -2029,6 +2029,11 @@ void connection_make_readable(Connection *conn) signal_listner(); } +void connection_make_readable_nolock(Connection *conn) +{ + conn->c_gettingber = 0; +} + /* * Figure out the operation completion rate for this connection */ @@ -2166,7 +2171,8 @@ connection_threadmain() Connection *conn = NULL; Operation *op; ber_tag_t tag = 0; - int need_wakeup; + int need_wakeup = 0; + int need_conn_release = 0; int thread_turbo_flag = 0; int ret = 0; int more_data = 0; @@ -2303,7 +2309,7 @@ connection_threadmain() * they are received off the wire. */ replication_connection = conn->c_isreplication_session; - if (tag != LDAP_REQ_UNBIND && (!thread_turbo_flag) && !more_data && !replication_connection) { + if ((tag != LDAP_REQ_UNBIND) && !thread_turbo_flag && !more_data && !replication_connection) { connection_make_readable(conn); } @@ -2350,53 +2356,75 @@ done: /* total number of ops for the server */ slapi_counter_increment(ops_completed); /* If this op isn't a persistent search, remove it */ + need_conn_release = 0; if ( !( pb->pb_op->o_flags & OP_FLAG_PS )) { /* delete from connection operation queue & decr refcnt */ PR_Lock( conn->c_mutex ); connection_remove_operation( conn, op ); - /* destroying the pblock will cause destruction of the operation - * so this must happend before releasing the connection - */ + /* destroying the pblock will cause destruction of the operation + * so this must happend before releasing the connection + */ slapi_pblock_destroy( pb ); - /* If we're in turbo mode, we keep our reference to the connection - alive */ + /* If we're in turbo mode, we keep our reference to the connection + alive */ if (!thread_turbo_flag && !more_data) { - connection_release_nolock (conn); - } + /* + * Don't release the connection now. + * But note down what to do. + */ + need_conn_release = 1; + } PR_Unlock( conn->c_mutex ); } else { /* the ps code acquires a ref to the conn - we need to release ours here */ PR_Lock( conn->c_mutex ); - connection_release_nolock (conn); + connection_release_nolock (conn); PR_Unlock( conn->c_mutex ); } - /* Since we didn't do so earlier, we need to make a replication connection readable again here */ - if ( ((1 == is_timedout) || (replication_connection && !thread_turbo_flag)) && !more_data) - connection_make_readable(conn); pb = NULL; if (doshutdown) { + PR_Lock(conn->c_mutex); + connection_make_readable_nolock(conn); + conn->c_threadnumber--; + connection_release_nolock(conn); + PR_Unlock(conn->c_mutex); + signal_listner(); return; } - if (!thread_turbo_flag && !more_data) { /* Don't do this in turbo mode */ - PR_Lock( conn->c_mutex ); - /* if the threadnumber of now below the maximum, wakeup - * the listener thread so that we start polling on this - * connection again - */ - /* DBDB I think this code is bogus -- we already signaled the listener above here */ - if (conn->c_threadnumber == config_get_maxthreadsperconn()) - need_wakeup = 1; - else - need_wakeup = 0; - conn->c_threadnumber--; - PR_Unlock( conn->c_mutex ); - - if (need_wakeup) - signal_listner(); + if (!more_data) { /* no more data in the buffer */ + if (!thread_turbo_flag) { /* Don't do this in turbo mode */ + /* Since we didn't do so earlier, we need to make a + * replication connection readable again here */ + PR_Lock( conn->c_mutex ); + if (replication_connection || (1 == is_timedout)) { + connection_make_readable_nolock(conn); + need_wakeup = 1; + } + /* if the threadnumber of now below the maximum, wakeup + * the listener thread so that we start polling on this + * connection again + */ + if (!need_wakeup) { + if (conn->c_threadnumber == config_get_maxthreadsperconn()) + need_wakeup = 1; + else + need_wakeup = 0; + } + conn->c_threadnumber--; + if (need_conn_release) { + connection_release_nolock(conn); + } + PR_Unlock( conn->c_mutex ); + /* Call signal_listner after releasing the + * connection if required. */ + if (need_wakeup) { + signal_listner(); + } + } else if (1 == is_timedout) { + connection_make_readable(conn); + } } - - } /* while (1) */ }
0
b7ce2a848e02512ea2ed1fe77e784fbf02a4b42c
389ds/389-ds-base
Issue 4253 - Container bind mount schema Bug Description: When you mount a volume with schema into container, instance creation fails with: ``` Traceback (most recent call last): File "/usr/libexec/dirsrv/dscontainer", line 489, in <module> begin_magic() ~~~~~~~~~~~^^ File "/usr/libexec/dirsrv/dscontainer", line 279, in begin_magic if not sds.create_from_args(g2b.collect(), s2b.collect()): ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/instance/setup.py", line 759, in create_from_args self._install_ds(general, slapd, backends) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/instance/setup.py", line 903, in _install_ds _ds_shutil_copytree(os.path.join(slapd['sysconf_dir'], 'dirsrv/schema'), slapd['schema_dir']) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/__init__.py", line 230, in _ds_shutil_copytree os.makedirs(dst) ~~~~~~~~~~~^^^^^ File "<frozen os>", line 227, in makedirs FileExistsError: [Errno 17] File exists: '/etc/dirsrv/slapd-localhost/schema' ``` `_ds_shutil_copytree()` is an outdated copy of the `shutil.copytree()` from Python 3.5. In the later versions `dirs_exist_ok` parameter was introduced, but it was never backported to our implementation. Fix Description: Instead of the custom implementation, use standard `shutil.copytree()` function, but ignore existing directories (`dirs_exist_ok=True`) and use `copy` instead of `copy2` to ignore file metadata. Fixes: https://github.com/389ds/389-ds-base/issues/4253 Reviewed by: @mreynolds389, @droideck (Thanks!)
commit b7ce2a848e02512ea2ed1fe77e784fbf02a4b42c Author: Viktor Ashirov <[email protected]> Date: Mon May 12 14:37:59 2025 +0200 Issue 4253 - Container bind mount schema Bug Description: When you mount a volume with schema into container, instance creation fails with: ``` Traceback (most recent call last): File "/usr/libexec/dirsrv/dscontainer", line 489, in <module> begin_magic() ~~~~~~~~~~~^^ File "/usr/libexec/dirsrv/dscontainer", line 279, in begin_magic if not sds.create_from_args(g2b.collect(), s2b.collect()): ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/instance/setup.py", line 759, in create_from_args self._install_ds(general, slapd, backends) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/instance/setup.py", line 903, in _install_ds _ds_shutil_copytree(os.path.join(slapd['sysconf_dir'], 'dirsrv/schema'), slapd['schema_dir']) ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.13/site-packages/lib389/__init__.py", line 230, in _ds_shutil_copytree os.makedirs(dst) ~~~~~~~~~~~^^^^^ File "<frozen os>", line 227, in makedirs FileExistsError: [Errno 17] File exists: '/etc/dirsrv/slapd-localhost/schema' ``` `_ds_shutil_copytree()` is an outdated copy of the `shutil.copytree()` from Python 3.5. In the later versions `dirs_exist_ok` parameter was introduced, but it was never backported to our implementation. Fix Description: Instead of the custom implementation, use standard `shutil.copytree()` function, but ignore existing directories (`dirs_exist_ok=True`) and use `copy` instead of `copy2` to ignore file metadata. Fixes: https://github.com/389ds/389-ds-base/issues/4253 Reviewed by: @mreynolds389, @droideck (Thanks!) diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index a68ecd19f..0ddfca8ae 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -214,61 +214,6 @@ def pid_from_file(pidfile): pass return pid -def _ds_shutil_copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, - ignore_dangling_symlinks=False): - """Recursively copy a directory tree. - This is taken from /usr/lib64/python3.5/shutil.py, but removes the - copystat function at the end. Why? Because in a container without - privileges, we don't have access to set xattr. But copystat attempts to - set the xattr when we are root, which causes the copy to fail. Remove it! - """ - names = os.listdir(src) - if ignore is not None: - ignored_names = ignore(src, names) - else: - ignored_names = set() - - os.makedirs(dst) - errors = [] - for name in names: - if name in ignored_names: - continue - srcname = os.path.join(src, name) - dstname = os.path.join(dst, name) - try: - if os.path.islink(srcname): - linkto = os.readlink(srcname) - if symlinks: - # We can't just leave it to `copy_function` because legacy - # code with a custom `copy_function` may rely on copytree - # doing the right thing. - os.symlink(linkto, dstname) - shutil.copystat( - srcname, dstname, follow_symlinks=not symlinks - ) - else: - # ignore dangling symlink if the flag is on - if not os.path.exists(linkto) and ignore_dangling_symlinks: - continue - # otherwise let the copy occurs. copy2 will raise an error - if os.path.isdir(srcname): - _ds_shutil_copytree(srcname, dstname, symlinks, ignore, - copy_function) - else: - copy_function(srcname, dstname) - elif os.path.isdir(srcname): - _ds_shutil_copytree(srcname, dstname, symlinks, ignore, copy_function) - else: - # Will raise a SpecialFileError for unsupported file types - copy_function(srcname, dstname) - # catch the Error from the recursive copytree so that we can - # continue with other files - except Error as err: - errors.extend(err.args[0]) - except OSError as why: - errors.append((srcname, dstname, str(why))) - return dst - class DirSrv(SimpleLDAPObject, object): diff --git a/src/lib389/lib389/instance/setup.py b/src/lib389/lib389/instance/setup.py index 41f59249e..30a8e628a 100644 --- a/src/lib389/lib389/instance/setup.py +++ b/src/lib389/lib389/instance/setup.py @@ -18,7 +18,7 @@ import socket import subprocess import getpass import configparser -from lib389 import _ds_shutil_copytree, DirSrv +from lib389 import DirSrv from lib389._constants import * from lib389.properties import * from lib389.passwd import password_hash, password_generate @@ -900,7 +900,13 @@ class SetupDs(object): # This is a little fragile, make it better. # It won't matter when we move schema to usr anyway ... - _ds_shutil_copytree(os.path.join(slapd['sysconf_dir'], 'dirsrv/schema'), slapd['schema_dir']) + shutil.copytree( + os.path.join(slapd["sysconf_dir"], "dirsrv/schema"), + slapd["schema_dir"], + copy_function=shutil.copy, + # Schema directory might be bind mounted, ingore it + dirs_exist_ok=True, + ) os.chown(slapd['schema_dir'], slapd['user_uid'], slapd['group_gid']) os.chmod(slapd['schema_dir'], 0o770)
0
ad8f6417258a3eca48da8cd8778721fdecc61078
389ds/389-ds-base
Resolves: 238630 Summary: Remove changelog db file when replica config is removed.
commit ad8f6417258a3eca48da8cd8778721fdecc61078 Author: Nathan Kinder <[email protected]> Date: Fri Oct 12 17:22:54 2007 +0000 Resolves: 238630 Summary: Remove changelog db file when replica config is removed. diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index 7d16cd8c6..49aabc668 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -6391,20 +6391,24 @@ static void _cl5DBCloseFile (void **data) _cl5WriteRUV (file, PR_FALSE); } - /* close file */ + /* close the db */ if (file->db) file->db->close(file->db, 0); if (file->flags & DB_FILE_DELETED) - { - PR_snprintf(fullpathname, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, file->name); - if (PR_Delete(fullpathname) != PR_SUCCESS) + { + int rc = 0; + /* We need to use the libdb API to delete the files, otherwise we'll + * run into problems when we try to checkpoint transactions later. */ + PR_snprintf(fullpathname, MAXPATHLEN, "%s/%s", s_cl5Desc.dbDir, file->name); + rc = s_cl5Desc.dbEnv->dbremove(s_cl5Desc.dbEnv, 0, fullpathname, 0, 0); + if (rc != 0) { - slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: " - "failed to remove (%s) file; NSPR error - %d\n", file->name, PR_GetError ()); - - } - } + slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name_cl, "_cl5DBCloseFile: " + "failed to remove (%s) file; libdb error - %d (%s)\n", file->name, + rc, dblayer_strerror(rc)); + } + } /* slapi_ch_free accepts NULL pointer */ slapi_ch_free ((void**)&file->name); diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index a575f1f3d..af5b6cd74 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -460,9 +460,17 @@ replica_config_delete (Slapi_PBlock *pb, Slapi_Entry* e, Slapi_Entry* entryAfter if (mtnode_ext->replica) { + char ebuf[BUFSIZ]; + /* remove object from the hash */ r = (Replica*)object_get_data (mtnode_ext->replica); PR_ASSERT (r); + /* The changelog for this replica is no longer valid, so we should remove it. */ + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "replica_config_delete: " + "Warning: The changelog for replica %s is no longer valid since " + "the replica config is being deleted. Removing the changelog.\n", + escape_string(slapi_sdn_get_dn(replica_get_root(r)),ebuf)); + cl5DeleteDBSync(mtnode_ext->replica); replica_delete_by_name (replica_get_name (r)); object_release (mtnode_ext->replica); mtnode_ext->replica = NULL;
0
91f3e592713ea58602412ed773a497583f2ebd6c
389ds/389-ds-base
Ticket 48808 - Add test case Description: Add test case for paged results search returns the blank list of entries issue. Bug description: After series of actions, paged result search that should returns list of entries returns blank list of entries. It is hardly reproducible manually, but it is easy to reproduce with python automation. https://fedorahosted.org/389/ticket/48808 Reviewed by: nhosoi and wbrown (Thanks!)
commit 91f3e592713ea58602412ed773a497583f2ebd6c Author: Simon Pichugin <[email protected]> Date: Thu Apr 28 11:49:24 2016 +0200 Ticket 48808 - Add test case Description: Add test case for paged results search returns the blank list of entries issue. Bug description: After series of actions, paged result search that should returns list of entries returns blank list of entries. It is hardly reproducible manually, but it is easy to reproduce with python automation. https://fedorahosted.org/389/ticket/48808 Reviewed by: nhosoi and wbrown (Thanks!) diff --git a/dirsrvtests/tests/tickets/ticket48808_test.py b/dirsrvtests/tests/tickets/ticket48808_test.py new file mode 100644 index 000000000..3dbceac3f --- /dev/null +++ b/dirsrvtests/tests/tickets/ticket48808_test.py @@ -0,0 +1,337 @@ +import time +import ldap +import logging +import pytest +from random import sample +from ldap.controls import SimplePagedResultsControl +from lib389 import DirSrv, Entry, tools, tasks +from lib389.tools import DirSrvTools +from lib389._constants import * +from lib389.properties import * +from lib389.tasks import * +from lib389.utils import * + +logging.getLogger(__name__).setLevel(logging.DEBUG) +log = logging.getLogger(__name__) + +TEST_USER_NAME = 'simplepaged_test' +TEST_USER_DN = 'uid=%s,%s' % (TEST_USER_NAME, DEFAULT_SUFFIX) +TEST_USER_PWD = 'simplepaged_test' + + +class TopologyStandalone(object): + def __init__(self, standalone): + standalone.open() + self.standalone = standalone + + [email protected](scope="module") +def topology(request): + # Creating standalone instance ... + standalone = DirSrv(verbose=False) + args_instance[SER_HOST] = HOST_STANDALONE + args_instance[SER_PORT] = PORT_STANDALONE + args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE + args_instance[SER_CREATION_SUFFIX] = DEFAULT_SUFFIX + args_standalone = args_instance.copy() + standalone.allocate(args_standalone) + instance_standalone = standalone.exists() + if instance_standalone: + standalone.delete() + standalone.create() + standalone.open() + + # Delete each instance in the end + def fin(): + standalone.delete() + request.addfinalizer(fin) + + # Clear out the tmp dir + standalone.clearTmpDir(__file__) + + return TopologyStandalone(standalone) + + [email protected](scope="module") +def test_user(topology): + """User for binding operation""" + + try: + topology.standalone.add_s(Entry((TEST_USER_DN, { + 'objectclass': 'top person'.split(), + 'objectclass': 'organizationalPerson', + 'objectclass': 'inetorgperson', + 'cn': TEST_USER_NAME, + 'sn': TEST_USER_NAME, + 'userpassword': TEST_USER_PWD, + 'mail': '%[email protected]' % TEST_USER_NAME, + 'uid': TEST_USER_NAME + }))) + except ldap.LDAPError as e: + log.error('Failed to add user (%s): error (%s)' % (TEST_USER_DN, + e.message['desc'])) + raise e + + +def add_users(topology, users_num): + """Add users to the default suffix + and return a list of added user DNs. + """ + + users_list = [] + log.info('Adding %d users' % users_num) + for num in sample(range(1000), users_num): + num_ran = int(round(num)) + USER_NAME = 'test%05d' % num_ran + USER_DN = 'uid=%s,%s' % (USER_NAME, DEFAULT_SUFFIX) + users_list.append(USER_DN) + try: + topology.standalone.add_s(Entry((USER_DN, { + 'objectclass': 'top person'.split(), + 'objectclass': 'organizationalPerson', + 'objectclass': 'inetorgperson', + 'cn': USER_NAME, + 'sn': USER_NAME, + 'userpassword': 'pass%s' % num_ran, + 'mail': '%[email protected]' % USER_NAME, + 'uid': USER_NAME + }))) + except ldap.LDAPError as e: + log.error('Failed to add user (%s): error (%s)' % (USER_DN, + e.message['desc'])) + raise e + return users_list + + +def del_users(topology, users_list): + """Delete users with DNs from given list""" + + log.info('Deleting %d users' % len(users_list)) + for user_dn in users_list: + try: + topology.standalone.delete_s(user_dn) + except ldap.LDAPError as e: + log.error('Failed to delete user (%s): error (%s)' % (user_dn, + e.message['desc'])) + raise e + + +def change_conf_attr(topology, suffix, attr_name, attr_value): + """Change configurational attribute in the given suffix. + Funtion returns previous attribute value. + """ + + try: + entries = topology.standalone.search_s(suffix, ldap.SCOPE_BASE, + 'objectclass=top', + [attr_name]) + attr_value_bck = entries[0].data.get(attr_name) + log.info('Set %s to %s. Previous value - %s. Modified suffix - %s.' % ( + attr_name, attr_value, attr_value_bck, suffix)) + if attr_value is None: + topology.standalone.modify_s(suffix, [(ldap.MOD_DELETE, + attr_name, + attr_value)]) + else: + topology.standalone.modify_s(suffix, [(ldap.MOD_REPLACE, + attr_name, + attr_value)]) + except ldap.LDAPError as e: + log.error('Failed to change attr value (%s): error (%s)' % (attr_name, + e.message['desc'])) + raise e + + return attr_value_bck + + +def paged_search(topology, controls, search_flt, searchreq_attrlist): + """Search at the DEFAULT_SUFFIX with ldap.SCOPE_SUBTREE + using Simple Paged Control(should the first item in the + list controls. + Return the list with results summarized from all pages + """ + + pages = 0 + pctrls = [] + all_results = [] + req_ctrl = controls[0] + msgid = topology.standalone.search_ext(DEFAULT_SUFFIX, + ldap.SCOPE_SUBTREE, + search_flt, + searchreq_attrlist, + serverctrls=controls) + while True: + log.info('Getting page %d' % (pages,)) + rtype, rdata, rmsgid, rctrls = topology.standalone.result3(msgid) + all_results.extend(rdata) + pages += 1 + pctrls = [ + c + for c in rctrls + if c.controlType == SimplePagedResultsControl.controlType + ] + + if pctrls: + if pctrls[0].cookie: + # Copy cookie from response control to request control + req_ctrl.cookie = pctrls[0].cookie + msgid = topology.standalone.search_ext(DEFAULT_SUFFIX, + ldap.SCOPE_SUBTREE, + search_flt, + searchreq_attrlist, + serverctrls=controls) + else: + break # no more pages available + else: + break + + assert not pctrls[0].cookie + return all_results + + +def test_ticket48808(topology, test_user): + log.info('Run multiple paging controls on a single connection') + users_num = 100 + page_size = 30 + users_list = add_users(topology, users_num) + search_flt = r'(uid=test*)' + searchreq_attrlist = ['dn', 'sn'] + + log.info('Set user bind') + topology.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) + + log.info('Create simple paged results control instance') + req_ctrl = SimplePagedResultsControl(True, size=page_size, cookie='') + controls = [req_ctrl] + + for ii in xrange(3): + log.info('Iteration %d' % ii) + msgid = topology.standalone.search_ext(DEFAULT_SUFFIX, + ldap.SCOPE_SUBTREE, + search_flt, + searchreq_attrlist, + serverctrls=controls) + rtype, rdata, rmsgid, rctrls = topology.standalone.result3(msgid) + pctrls = [ + c + for c in rctrls + if c.controlType == SimplePagedResultsControl.controlType + ] + + req_ctrl.cookie = pctrls[0].cookie + msgid = topology.standalone.search_ext(DEFAULT_SUFFIX, + ldap.SCOPE_SUBTREE, + search_flt, + searchreq_attrlist, + serverctrls=controls) + log.info('Set Directory Manager bind back') + topology.standalone.simple_bind_s(DN_DM, PASSWORD) + del_users(topology, users_list) + + log.info('Abandon the search') + users_num = 10 + page_size = 0 + users_list = add_users(topology, users_num) + search_flt = r'(uid=test*)' + searchreq_attrlist = ['dn', 'sn'] + + log.info('Set user bind') + topology.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) + + log.info('Create simple paged results control instance') + req_ctrl = SimplePagedResultsControl(True, size=page_size, cookie='') + controls = [req_ctrl] + + msgid = topology.standalone.search_ext(DEFAULT_SUFFIX, + ldap.SCOPE_SUBTREE, + search_flt, + searchreq_attrlist, + serverctrls=controls) + rtype, rdata, rmsgid, rctrls = topology.standalone.result3(msgid) + pctrls = [ + c + for c in rctrls + if c.controlType == SimplePagedResultsControl.controlType + ] + assert not pctrls[0].cookie + + log.info('Set Directory Manager bind back') + topology.standalone.simple_bind_s(DN_DM, PASSWORD) + del_users(topology, users_list) + + log.info("Search should fail with 'nsPagedSizeLimit = 5'" + "and 'nsslapd-pagedsizelimit = 15' with 10 users") + conf_attr = '15' + user_attr = '5' + expected_rs = ldap.SIZELIMIT_EXCEEDED + users_num = 10 + page_size = 10 + users_list = add_users(topology, users_num) + search_flt = r'(uid=test*)' + searchreq_attrlist = ['dn', 'sn'] + conf_attr_bck = change_conf_attr(topology, DN_CONFIG, + 'nsslapd-pagedsizelimit', conf_attr) + user_attr_bck = change_conf_attr(topology, TEST_USER_DN, + 'nsPagedSizeLimit', user_attr) + + log.info('Set user bind') + topology.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) + + log.info('Create simple paged results control instance') + req_ctrl = SimplePagedResultsControl(True, size=page_size, cookie='') + controls = [req_ctrl] + + log.info('Expect to fail with SIZELIMIT_EXCEEDED') + with pytest.raises(expected_rs): + all_results = paged_search(topology, controls, + search_flt, searchreq_attrlist) + + log.info('Set Directory Manager bind back') + topology.standalone.simple_bind_s(DN_DM, PASSWORD) + del_users(topology, users_list) + change_conf_attr(topology, DN_CONFIG, + 'nsslapd-pagedsizelimit', conf_attr_bck) + change_conf_attr(topology, TEST_USER_DN, + 'nsPagedSizeLimit', user_attr_bck) + + log.info("Search should pass with 'nsPagedSizeLimit = 15'" + "and 'nsslapd-pagedsizelimit = 5' with 10 users") + conf_attr = '5' + user_attr = '15' + users_num = 10 + page_size = 10 + users_list = add_users(topology, users_num) + search_flt = r'(uid=test*)' + searchreq_attrlist = ['dn', 'sn'] + conf_attr_bck = change_conf_attr(topology, DN_CONFIG, + 'nsslapd-pagedsizelimit', conf_attr) + user_attr_bck = change_conf_attr(topology, TEST_USER_DN, + 'nsPagedSizeLimit', user_attr) + + log.info('Set user bind') + topology.standalone.simple_bind_s(TEST_USER_DN, TEST_USER_PWD) + + log.info('Create simple paged results control instance') + req_ctrl = SimplePagedResultsControl(True, size=page_size, cookie='') + controls = [req_ctrl] + + log.info('Search should PASS') + all_results = paged_search(topology, controls, + search_flt, searchreq_attrlist) + log.info('%d results' % len(all_results)) + assert len(all_results) == len(users_list) + + log.info('Set Directory Manager bind back') + topology.standalone.simple_bind_s(DN_DM, PASSWORD) + del_users(topology, users_list) + change_conf_attr(topology, DN_CONFIG, + 'nsslapd-pagedsizelimit', conf_attr_bck) + change_conf_attr(topology, TEST_USER_DN, + 'nsPagedSizeLimit', user_attr_bck) + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE)
0
c1cc0acdaf2a1bdd15b4056b396ee6757e21126e
389ds/389-ds-base
Issue 50130 - Building RPMs on RHEL8 fails Description: Due to an incorrect path in a "mv" command in 389-ds-base.spec.in, building RPMs on RHEL8 failed https://pagure.io/389-ds-base/issue/50130 Reviewed by: vashirov & wibrown
commit c1cc0acdaf2a1bdd15b4056b396ee6757e21126e Author: Marc Muehlfeld <[email protected]> Date: Tue Jan 8 15:01:18 2019 +0100 Issue 50130 - Building RPMs on RHEL8 fails Description: Due to an incorrect path in a "mv" command in 389-ds-base.spec.in, building RPMs on RHEL8 failed https://pagure.io/389-ds-base/issue/50130 Reviewed by: vashirov & wibrown diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index 8aee72336..25261956a 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -409,7 +409,7 @@ make DESTDIR="$RPM_BUILD_ROOT" install # Cockpit branding, and directory and file list %if 0%{?rhel} > 7 -mv -f %{buildroot}%{_datadir}/cockpit/389-console/src/rhds-banner.html %{buildroot}%{_datadir}/cockpit/389-console/src/banner.html +mv -f %{buildroot}%{_datadir}/cockpit/389-console/rhds-banner.html %{buildroot}%{_datadir}/cockpit/389-console/banner.html %endif find %{buildroot}%{_datadir}/cockpit/389-console -type d | sed -e "s@%{buildroot}@@" | sed -e 's/^/\%dir /' > cockpit.list find %{buildroot}%{_datadir}/cockpit/389-console -type f | sed -e "s@%{buildroot}@@" >> cockpit.list
0
5b0cbddc4f8a7b107eb00ec39d14792e5b6ffd83
389ds/389-ds-base
Issue 4218 - Verify the new wtime and optime access log keywords (#4397) Description: Add a test case to dirsrvtests/tests/suites/ds_logs/ds_logs_test.py: test_optime_and_wtime_keywords. It tests that the new optime and wtime keywords are present in the access log and have correct values Also, adapt test_etime_order_of_magnitude adapted to the new RESULT string format in the access log Relates: #4218 Reviewed by: @droideck, @Firstyear (Thanks!)
commit 5b0cbddc4f8a7b107eb00ec39d14792e5b6ffd83 Author: sgouvern <[email protected]> Date: Tue Nov 3 14:32:06 2020 +0100 Issue 4218 - Verify the new wtime and optime access log keywords (#4397) Description: Add a test case to dirsrvtests/tests/suites/ds_logs/ds_logs_test.py: test_optime_and_wtime_keywords. It tests that the new optime and wtime keywords are present in the access log and have correct values Also, adapt test_etime_order_of_magnitude adapted to the new RESULT string format in the access log Relates: #4218 Reviewed by: @droideck, @Firstyear (Thanks!) diff --git a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py index 0689ee60f..b02b5806a 100644 --- a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py +++ b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py @@ -20,6 +20,7 @@ from lib389._constants import DEFAULT_SUFFIX, LOG_ACCESS_LEVEL from lib389.utils import ds_is_older, ds_is_newer import ldap import glob +import re pytestmark = pytest.mark.tier1 @@ -774,7 +775,7 @@ def test_etime_at_border_of_second(topology_st, clean_access_logs): assert not invalid_etime [email protected](ds_is_older('1.3.10.1'), reason="Fail because of bug 1749236") [email protected](ds_is_older('1.3.10.1', '1.4.1'), reason="Fail because of bug 1749236") @pytest.mark.bz1749236 def test_etime_order_of_magnitude(topology_st, clean_access_logs, remove_users, disable_access_log_buffering): """Test that the etime reported in the access log has a correct order of magnitude @@ -835,21 +836,101 @@ def test_etime_order_of_magnitude(topology_st, clean_access_logs, remove_users, assert len(result_str) > 0 # The result_str returned looks like : - # [23/Apr/2020:06:06:14.366429900 -0400] conn=1 op=93 RESULT err=0 tag=101 nentries=30 etime=0.005723017 - + # For ds older than 1.4.3.8: [23/Apr/2020:06:06:14.366429900 -0400] conn=1 op=93 RESULT err=0 tag=101 nentries=30 etime=0.005723017 + # For ds newer than 1.4.3.8: [21/Oct/2020:09:27:50.095209871 -0400] conn=1 op=96 RESULT err=0 tag=101 nentries=30 wtime=0.000412584 optime=0.005428971 etime=0.005836077 + log.info('get the operation end time from the RESULT string') # Here we are getting the sec.nanosec part of the date, '14.366429900' in the above example end_time = (result_str.split()[0]).split(':')[3] log.info('get the logged etime for the operation from the RESULT string') # Here we are getting the etime value, '0.005723017' in the example above - etime = result_str.split()[8].split('=')[1][:-3] + if ds_is_older('1.4.3.8'): + etime = result_str.split()[8].split('=')[1][:-3] + else: + etime = result_str.split()[10].split('=')[1][:-3] log.info('Calculate the ratio between logged etime for the operation and elapsed time from its start time to its end time - should be around 1') etime_ratio = (Decimal(end_time) - Decimal(start_time)) // Decimal(etime) assert etime_ratio <= 1 [email protected](ds_is_older('1.4.3.8'), reason="Fail because of bug 1850275") [email protected] +def test_optime_and_wtime_keywords(topology_st, clean_access_logs, remove_users, disable_access_log_buffering): + """Test that the new optime and wtime keywords are present in the access log and have correct values + + :id: dfb4a49d-1cfc-400e-ba43-c107f58d62cf + :setup: Standalone instance + :steps: + 1. Unset log buffering for the access log + 2. Delete potential existing access logs + 3. Add users + 4. Search users + 5. Parse the access log looking for the SRCH operation log + 6. From the SRCH string get the op number of the operation + 7. From the op num find the associated RESULT string in the access log + 8. Search for the wtime optime keywords in the RESULT string + 9. From the RESULT string get the wtime, optime and etime values for the operation + 10. Check that optime + wtime is approximatively etime + :expectedresults: + 1. access log buffering is off + 2. Previously existing access logs are deleted + 3. Users are successfully added + 4. Search operation is successful + 5. SRCH operation log string is catched + 6. op number is collected + 7. RESULT string is catched from the access log + 8. wtime and optime keywords are collected + 9. wtime, optime and etime values are collected + 10. (optime + wtime) =~ etime + """ + + log.info('add_users') + add_users(topology_st.standalone, 30) + + log.info ('search users') + search_users(topology_st.standalone) + + log.info('parse the access logs to get the SRCH string') + # Here we are looking at the whole string logged for the search request with base ou=People,dc=example,dc=com + search_str = str(topology_st.standalone.ds_access_log.match(r'.*SRCH base="ou=People,dc=example,dc=com.*'))[1:-1] + assert len(search_str) > 0 + + # the search_str returned looks like : + # [22/Oct/2020:09:47:11.951316798 -0400] conn=1 op=96 SRCH base="ou=People,dc=example,dc=com" scope=2 filter="(&(objectClass=account)(objectClass=posixaccount)(objectClass=inetOrgPerson)(objectClass=organizationalPerson))" attrs="distinguishedName" + + log.info('get the OP number from the SRCH string') + # Here we are getting the op number, 'op=96' in the above example + op_num = search_str.split()[3] + + log.info('get the RESULT string matching the SRCH op number') + # Here we are looking at the RESULT string for the above search op, 'op=96' in this example + result_str = str(topology_st.standalone.ds_access_log.match(r'.*{} RESULT*'.format(op_num)))[1:-1] + assert len(result_str) > 0 + + # The result_str returned looks like : + # [22/Oct/2020:09:47:11.963276018 -0400] conn=1 op=96 RESULT err=0 tag=101 nentries=30 wtime=0.000180294 optime=0.011966632 etime=0.012141311 + log.info('Search for the wtime keyword in the RESULT string') + assert re.search('wtime', result_str) + + log.info('get the wtime value from the RESULT string') + wtime_value = result_str.split()[8].split('=')[1][:-3] + + log.info('Search for the optime keyword in the RESULT string') + assert re.search('optime', result_str) + + log.info('get the optime value from the RESULT string') + optime_value = result_str.split()[9].split('=')[1][:-3] + + log.info('get the etime value from the RESULT string') + etime_value = result_str.split()[10].split('=')[1][:-3] + + log.info('Check that (wtime + optime) is approximately equal to etime i.e. their ratio is 1') + etime_ratio = (Decimal(wtime_value) + Decimal(optime_value)) // Decimal(etime_value) + assert etime_ratio == 1 + + @pytest.mark.xfail(ds_is_older('1.3.10.1'), reason="May fail because of bug 1662461") @pytest.mark.bz1662461 @pytest.mark.ds50428
0
17f3bef9adfcd6bf999fbe02cb13dd4c4177b3b3
389ds/389-ds-base
Ticket 48085 - Add single master replication test suite Description: Port test suite from TET. - Check that no crash happens during mail attribute replication - Check that LastUpdate replica attributes show right values, when no initialization has happened. Reviewed by: wibrown (Thanks!) https://fedorahosted.org/389/ticket/48085
commit 17f3bef9adfcd6bf999fbe02cb13dd4c4177b3b3 Author: Simon Pichugin <[email protected]> Date: Mon Jan 23 11:32:01 2017 +0100 Ticket 48085 - Add single master replication test suite Description: Port test suite from TET. - Check that no crash happens during mail attribute replication - Check that LastUpdate replica attributes show right values, when no initialization has happened. Reviewed by: wibrown (Thanks!) https://fedorahosted.org/389/ticket/48085 diff --git a/dirsrvtests/tests/suites/replication/single_master_test.py b/dirsrvtests/tests/suites/replication/single_master_test.py new file mode 100644 index 000000000..a743d2ce4 --- /dev/null +++ b/dirsrvtests/tests/suites/replication/single_master_test.py @@ -0,0 +1,167 @@ +import pytest +from lib389.tasks import * +from lib389.utils import * +from lib389.topologies import topology_m1c1 as topo_r # Replication +from lib389.topologies import topology_i2 as topo_nr # No replication + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + +TEST_USER_NAME = 'smrepl_test' +TEST_USER_DN = 'uid={},{}'.format(TEST_USER_NAME, DEFAULT_SUFFIX) +TEST_USER_PWD = 'smrepl_test' + + [email protected] +def test_user(topo_r, request): + """User for binding operation""" + + log.info('Adding user {}'.format(TEST_USER_DN)) + try: + topo_r.ms["master1"].add_s(Entry((TEST_USER_DN, { + 'objectclass': 'top person'.split(), + 'objectclass': 'organizationalPerson', + 'objectclass': 'inetorgperson', + 'cn': TEST_USER_NAME, + 'sn': TEST_USER_NAME, + 'userpassword': TEST_USER_PWD, + 'mail': '{}@redhat.com'.format(TEST_USER_NAME), + 'uid': TEST_USER_NAME + }))) + except ldap.LDAPError as e: + log.error('Failed to add user (%s): error (%s)' % (TEST_USER_DN, + e.message['desc'])) + raise e + + def fin(): + log.info('Deleting user {}'.format(TEST_USER_DN)) + topo_r.ms["master1"].delete_s(TEST_USER_DN) + + request.addfinalizer(fin) + + [email protected](scope="module") +def replica_without_init(topo_nr): + """Enable replica without initialization""" + + master = topo_nr.ins["standalone1"] + consumer = topo_nr.ins["standalone2"] + + master.replica.enableReplication(suffix=DEFAULT_SUFFIX, role=REPLICAROLE_MASTER, + replicaId=REPLICAID_MASTER_1) + consumer.replica.enableReplication(suffix=DEFAULT_SUFFIX, role=REPLICAROLE_CONSUMER) + properties = {RA_NAME: 'meTo_{}:{}'.format(consumer.host, str(consumer.port)), + RA_BINDDN: defaultProperties[REPLICATION_BIND_DN], + RA_BINDPW: defaultProperties[REPLICATION_BIND_PW], + RA_METHOD: defaultProperties[REPLICATION_BIND_METHOD], + RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} + agmt = master.agreement.create(suffix=DEFAULT_SUFFIX, host=consumer.host, port=consumer.port, properties=properties) + + return agmt + + +def test_mail_attr_repl(topo_r, test_user): + """Check that no crash happens during mail attribute replication + + :Feature: Single master replication + + :Setup: Replication setup with master and consumer instances, + test user on master + + :Steps: 1. Check that user was replicated to consumer + 2. Back up mail database file + 3. Remove mail attribute from the user entry + 4. Restore mail database + 5. Search for the entry with a substring 'mail=user*' + 6. Search for the entry once again to make sure that server is alive + + :Assert: No crash happens + """ + + master = topo_r.ms["master1"] + consumer = topo_r.cs["consumer1"] + + log.info("Wait for a user to be replicated") + time.sleep(3) + + log.info("Check that replication is working") + entries = consumer.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "uid={}".format(TEST_USER_NAME), + ["uid"]) + assert entries, "User {} wasn't replicated successfully".format(TEST_USER_NAME) + + entries = consumer.backend.list(DEFAULT_SUFFIX) + db_dir = entries[0]["nsslapd-directory"] + mail_db = filter(lambda fl: fl.startswith("mail"), os.listdir(db_dir)) + assert mail_db, "mail.* wasn't found in {}" + mail_db_path = os.path.join(db_dir, mail_db[0]) + backup_path = os.path.join(DEFAULT_BACKUPDIR, mail_db[0]) + + consumer.stop() + log.info("Back up {} to {}".format(mail_db_path, backup_path)) + shutil.copyfile(mail_db_path, backup_path) + consumer.start() + + log.info("Remove 'mail' attr from master") + try: + master.modify_s(TEST_USER_DN, [(ldap.MOD_DELETE, 'mail', '{}@redhat.com'.format(TEST_USER_NAME))]) + except ldap.LDAPError as e: + log.error('Failed to delete att user {}: error {}'.format(TEST_USER_DN, e.message['desc'])) + raise e + + log.info("Wait for the replication to happen") + time.sleep(5) + + consumer.stop() + log.info("Restore {} to {}".format(backup_path, mail_db_path)) + shutil.copyfile(backup_path, mail_db_path) + consumer.start() + + log.info("Make a search for mail attribute in attempt to crash server") + consumer.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "mail={}*".format(TEST_USER_NAME), ["mail"]) + + log.info("Make sure that server hasn't crashed") + entries = consumer.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "uid={}".format(TEST_USER_NAME), + ["uid"]) + assert entries, "User {} wasn't replicated successfully".format(TEST_USER_NAME) + + +def test_mail_attr_repl(topo_nr, replica_without_init): + """Check that LastUpdate replica attributes show right values + + :Feature: Single master replication + + :Setup: Replication setup with master and consumer instances + without initialization + + :Steps: 1. Check nsds5replicaLastUpdateStart, nsds5replicaLastUpdateEnd, + nsds5replicaLastUpdateStatus attrs + + :Assert: nsds5replicaLastUpdateStart: 0, nsds5replicaLastUpdateEnd: 0 and + nsds5replicaLastUpdateStatus is not equal to + "0 Replica acquired successfully: Incremental update started" + """ + + master = topo_nr.ins["standalone1"] + consumer = topo_nr.ins["standalone2"] + + assert not master.testReplication(DEFAULT_SUFFIX, consumer) + + agmt = master.search_s(replica_without_init, ldap.SCOPE_BASE, "(objectClass=*)", + ["nsds5replicaLastUpdateStart", + "nsds5replicaLastUpdateEnd", + "nsds5replicaLastUpdateStatus"])[0] + + assert agmt["nsds5replicaLastUpdateStart"] == "19700101000000Z" + assert agmt["nsds5replicaLastUpdateEnd"] == "19700101000000Z" + assert "Replica acquired successfully" not in agmt["nsds5replicaLastUpdateStatus"] + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s %s" % CURRENT_FILE)
0
1cbd6d84dd0871af4955ebf93693e8b4331ab07e
389ds/389-ds-base
Ticket 47325 - Crash at shutdown on a replica aggrement Bug Description: This is a followup of the ticket https://fedorahosted.org/389/ticket/618 The RA thread are waited by the main daemon at shutdown. The problem is that the RA thread are not created with the right flag so they are not joinable. Fix Description: Use the correct creation flag PR_JOINABLE_THREAD In addition this fix introduce a bind timeout for the RA. It will take the one defined in the protocol (10 min per default). Ticket: https://fedorahosted.org/389/ticket/47325 Reviewed by: Mark Reynolds (thank you Mark !) Platforms tested: Fedora 17 Flag Day: no Doc impact: no
commit 1cbd6d84dd0871af4955ebf93693e8b4331ab07e Author: Thierry bordaz (tbordaz) <[email protected]> Date: Wed Apr 10 18:45:17 2013 +0200 Ticket 47325 - Crash at shutdown on a replica aggrement Bug Description: This is a followup of the ticket https://fedorahosted.org/389/ticket/618 The RA thread are waited by the main daemon at shutdown. The problem is that the RA thread are not created with the right flag so they are not joinable. Fix Description: Use the correct creation flag PR_JOINABLE_THREAD In addition this fix introduce a bind timeout for the RA. It will take the one defined in the protocol (10 min per default). Ticket: https://fedorahosted.org/389/ticket/47325 Reviewed by: Mark Reynolds (thank you Mark !) Platforms tested: Fedora 17 Flag Day: no Doc impact: no diff --git a/ldap/servers/plugins/replication/repl5_connection.c b/ldap/servers/plugins/replication/repl5_connection.c index b8b542e97..668abdaf3 100644 --- a/ldap/servers/plugins/replication/repl5_connection.c +++ b/ldap/servers/plugins/replication/repl5_connection.c @@ -1782,7 +1782,7 @@ bind_and_check_pwp(Repl_Connection *conn, char * binddn, char *password) const char *mech = bind_method_to_mech(conn->bindmethod); rc = slapi_ldap_bind(conn->ld, binddn, password, mech, NULL, - &ctrls, NULL, NULL); + &ctrls, &conn->timeout, NULL); if ( rc == LDAP_SUCCESS ) { diff --git a/ldap/servers/plugins/replication/repl5_protocol.c b/ldap/servers/plugins/replication/repl5_protocol.c index 76e018ab5..8373ba62d 100644 --- a/ldap/servers/plugins/replication/repl5_protocol.c +++ b/ldap/servers/plugins/replication/repl5_protocol.c @@ -369,9 +369,9 @@ prot_start(Repl_Protocol *rp) { rp->agmt_thread = PR_CreateThread(PR_USER_THREAD, prot_thread_main, (void *)rp, #if defined(__hpux) && defined(__ia64) - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, 524288L ); + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 524288L ); #else - PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD, SLAPD_DEFAULT_THREAD_STACKSIZE); + PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, SLAPD_DEFAULT_THREAD_STACKSIZE); #endif if (rp->agmt_thread == NULL) { diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index 3ca1139f7..5ac2fdd01 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -1126,7 +1126,19 @@ slapi_ldap_bind( if (msgidp) { /* let caller process result */ *msgidp = mymsgid; } else { /* process results */ - rc = ldap_result(ld, mymsgid, LDAP_MSG_ALL, timeout, &result); + struct timeval default_timeout, *bind_timeout; + + if ((timeout == NULL) || ((timeout->tv_sec == 0) && (timeout->tv_usec == 0))) { + /* Let's wait 1 min max to bind */ + default_timeout.tv_sec = 60; + default_timeout.tv_usec = 0; + + bind_timeout = &default_timeout; + } else { + /* take the one provided by the caller. It should be the one defined in the protocol */ + bind_timeout = timeout; + } + rc = ldap_result(ld, mymsgid, LDAP_MSG_ALL, bind_timeout, &result); if (-1 == rc) { /* error */ rc = slapi_ldap_get_lderrno(ld, NULL, NULL); slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind", @@ -1141,8 +1153,8 @@ slapi_ldap_bind( slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind", "Error: timeout after [%ld.%ld] seconds reading " "bind response for [%s] authentication mechanism [%s]\n", - timeout ? timeout->tv_sec : 0, - timeout ? timeout->tv_usec : 0, + bind_timeout ? bind_timeout->tv_sec : 0, + bind_timeout ? bind_timeout->tv_usec : 0, bindid ? bindid : "(anon)", mech ? mech : "SIMPLE"); goto done;
0
2031ed0d72680354d3363d9cf115ebf6f40a9b65
389ds/389-ds-base
Ticket 50224 - warnings on deprecated API usage Bug Description: There have been many cases of incorrect and invalid api usage. As we go on, we can't allow more usage of these apis to be added as it only puts more work on us in the future to remove. Fix Description: Add deprecation warnings to these apis, telling people they will be removed, and where their faulty code is. https://pagure.io/389-ds-base/issue/50224 Author: William Brown <[email protected]> Review by: mreynolds (Thanks!)
commit 2031ed0d72680354d3363d9cf115ebf6f40a9b65 Author: William Brown <[email protected]> Date: Fri Feb 15 13:55:48 2019 +1000 Ticket 50224 - warnings on deprecated API usage Bug Description: There have been many cases of incorrect and invalid api usage. As we go on, we can't allow more usage of these apis to be added as it only puts more work on us in the future to remove. Fix Description: Add deprecation warnings to these apis, telling people they will be removed, and where their faulty code is. https://pagure.io/389-ds-base/issue/50224 Author: William Brown <[email protected]> Review by: mreynolds (Thanks!) diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index 652129f4f..5b6b90ead 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -50,9 +50,10 @@ def import_example_ldif(topology_st): ldif = '%s/dirsrv/data/Example.ldif' % topology_st.standalone.get_data_dir() import_ldif = topology_st.standalone.get_ldif_dir() + "/Example.ldif" shutil.copyfile(ldif, import_ldif) - topology_st.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX, - input_file=import_ldif, - args={TASK_WAIT: True}) + + r = ImportTask(topology_st.standalone) + r.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX) + r.wait() @pytest.fixture(params=ROOTDSE_DEF_ATTR_LIST) @@ -260,13 +261,9 @@ def test_basic_import_export(topology_st, import_example_ldif): dbgen(topology_st.standalone, 50000, import_ldif, DEFAULT_SUFFIX) # Online - try: - topology_st.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX, - input_file=import_ldif, - args={TASK_WAIT: True}) - except ValueError: - log.fatal('test_basic_import_export: Online import failed') - assert False + r = ImportTask(topology_st.standalone) + r.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX) + r.wait() # Offline topology_st.standalone.stop() @@ -281,13 +278,11 @@ def test_basic_import_export(topology_st, import_example_ldif): # Online export export_ldif = ldif_dir + '/export.ldif' - exportTask = Tasks(topology_st.standalone) - try: - args = {TASK_WAIT: True} - exportTask.exportLDIF(DEFAULT_SUFFIX, None, export_ldif, args) - except ValueError: - log.fatal('test_basic_import_export: Online export failed') - assert False + + + r = ExportTask(topology_st.standalone) + r.export_suffix_to_ldif(ldiffile=export_ldif, suffix=DEFAULT_SUFFIX) + r.wait() # Offline export topology_st.standalone.stop() @@ -304,13 +299,10 @@ def test_basic_import_export(topology_st, import_example_ldif): ldif = '%s/dirsrv/data/Example.ldif' % topology_st.standalone.get_data_dir() import_ldif = topology_st.standalone.get_ldif_dir() + "/Example.ldif" shutil.copyfile(ldif, import_ldif) - try: - topology_st.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX, - input_file=import_ldif, - args={TASK_WAIT: True}) - except ValueError: - log.fatal('test_basic_import_export: Online import failed') - assert False + + r = ImportTask(topology_st.standalone) + r.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX) + r.wait() log.info('test_basic_import_export: PASSED') diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 5e91dbcc3..1d0d693c3 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -58,6 +58,10 @@ import json from shutil import copy2 import six +# Deprecation +import warnings +import inspect + from ldap.ldapobject import SimpleLDAPObject from ldap.cidict import cidict from ldap import LDAPError @@ -105,6 +109,8 @@ RE_DBMONATTRSUN = re.compile(r'^([a-zA-Z]+)-([a-zA-Z]+)$') # This controls pyldap debug levels TRACE_LEVEL = 0 +DEBUGGING = os.getenv('DEBUGGING', default=False) + # My logger logger = logging.getLogger(__name__) @@ -131,6 +137,59 @@ def wrapper(f, name): extract the raw data from the entry object to pass in. """ def inner(*args, **kwargs): + if name in [ + 'add_s', + 'bind_s', + 'delete_s', + 'modify_s', + 'modrdn_s', + 'rename_s', + 'sasl_interactive_bind_s', + 'search_s', + 'search_ext_s', + 'simple_bind_s', + 'unbind_s', + 'getEntry', + ] and not ('escapehatch' in kwargs and kwargs['escapehatch'] == 'i am sure'): + c_stack = inspect.stack() + frame = c_stack[1] + + + warnings.warn(DeprecationWarning("Use of raw ldap function %s. This will removed in a future release. Found in: %s:%s" % (name, frame.filename, frame.lineno))) + if not DEBUGGING: + sys.stderr.write(""" +________________________________________ +/ YOU ARE USING A DEPRECATED AND INVALID \\ +| LIB389 API. YOU PROBABLY WANT A | +| DSLDAPOBJECT INSTEAD! | +| | +| IN THE FUTURE THIS WILL CRASH YOUR | +| APPLICATION | +| | +\\ %s found at %s:%s / + ---------------------------------------- + \\ / \ //\\ + \\ |\\___/| / \\// \\\\ + /0 0 \\__ / // | \\ \\ + / / \\/_/ // | \\ \\ + @_^_@'/ \\/_ // | \\ \\ + //_^_/ \\/_ // | \\ \\ + ( //) | \\/// | \\ \\ + ( / /) _|_ / ) // | \\ _\\ + ( // /) '/,_ _ _/ ( ; -. | _ _\\.-~ .-~~~^-. + (( / / )) ,-{ _ `-.|.-~-. .~ `. + (( // / )) '/\\ / ~-. _ .-~ .-~^-. \\ + (( /// )) `. { } / \\ \\ + (( / )) .----~-.\\ \\-' .~ \\ `. \\^-. + ///.----..> \\ _ -~ `. ^-` ^-_ + ///-._ _ _ _ _ _ _}^ - - - - ~ ~-- ,.-~ + /.-~ + """ % (name, frame.filename, frame.lineno)) + # Later, we will add a sleep here to make it even more painful. + # Finally, it will raise an exception. + elif 'escapehatch' in kwargs: + kwargs.pop('escapehatch') + if name == 'result': objtype, data = f(*args, **kwargs) # data is either a 2-tuple or a list of 2-tuples @@ -292,7 +351,7 @@ class DirSrv(SimpleLDAPObject, object): else: super(DirSrv, self).__init__(uri, trace_level=TRACE_LEVEL) # self.start_tls_s() - self.simple_bind_s(ensure_str(self.binddn), self.bindpw) + self.simple_bind_s(ensure_str(self.binddn), self.bindpw, escapehatch='i am sure') def __add_brookers__(self): from lib389.config import Config @@ -999,22 +1058,22 @@ class DirSrv(SimpleLDAPObject, object): self.set_option(ldap.OPT_X_TLS_NEWCTX, 0) if starttls and not uri.startswith('ldaps'): - self.start_tls_s() + self.start_tls_s(escapehatch='i am sure') if saslmethod and sasltoken is not None: # Just pass the sasltoken in! - self.sasl_interactive_bind_s("", sasltoken) + self.sasl_interactive_bind_s("", sasltoken, escapehatch='i am sure') elif saslmethod and saslmethod.lower() == 'gssapi': """ Perform kerberos/gssapi authentication """ sasl_auth = ldap.sasl.gssapi("") - self.sasl_interactive_bind_s("", sasl_auth) + self.sasl_interactive_bind_s("", sasl_auth, escapehatch='i am sure') elif saslmethod == 'EXTERNAL': # Do nothing. sasl_auth = ldap.sasl.external() - self.sasl_interactive_bind_s("", sasl_auth) + self.sasl_interactive_bind_s("", sasl_auth, escapehatch='i am sure') elif saslmethod: # Unknown or unsupported method self.log.debug('Unsupported SASL method: %s', saslmethod) @@ -1025,14 +1084,14 @@ class DirSrv(SimpleLDAPObject, object): # do nothing: the bind is complete. self.log.debug("open(): Using root autobind ...") sasl_auth = ldap.sasl.external() - self.sasl_interactive_bind_s("", sasl_auth) + self.sasl_interactive_bind_s("", sasl_auth, escapehatch='i am sure') else: """ Do a simple bind """ try: - self.simple_bind_s(ensure_str(self.binddn), self.bindpw) + self.simple_bind_s(ensure_str(self.binddn), self.bindpw, escapehatch='i am sure') except ldap.SERVER_DOWN as e: # TODO add server info in exception self.log.debug("Cannot connect to %r", uri) @@ -1064,7 +1123,7 @@ class DirSrv(SimpleLDAPObject, object): # check that DirSrv was in DIRSRV_STATE_ONLINE state if self.state == DIRSRV_STATE_ONLINE: # Don't raise an error. Just move the state and return - self.unbind_s() + self.unbind_s(escapehatch='i am sure') self.state = DIRSRV_STATE_OFFLINE @@ -3331,11 +3390,11 @@ class DirSrv(SimpleLDAPObject, object): return status def delete_branch_s(self, basedn, scope, filterstr="(objectclass=*)", serverctrls=None, clientctrls=None): - ents = self.search_s(basedn, scope, filterstr) + ents = self.search_s(basedn, scope, filterstr, escapehatch='i am sure') for ent in sorted(ents, key=lambda e: len(e.dn), reverse=True): self.log.debug("Delete entry children %s", ent.dn) - self.delete_ext_s(ent.dn, serverctrls=serverctrls, clientctrls=clientctrls) + self.delete_ext_s(ent.dn, serverctrls=serverctrls, clientctrls=clientctrls, escapehatch='i am sure') def backup_online(self, archive=None, db_type=None): """Creates a backup of the database""" diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 1dd882566..9c5e0bdbe 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -121,13 +121,13 @@ class DSLdapObject(DSLogging): def __str__(self): return self.__unicode__() - def raw_entry(self): + def _unsafe_raw_entry(self): """Get an Entry object :returns: Entry object """ - return self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + return self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] def exists(self): """Check if the entry exists @@ -136,7 +136,7 @@ class DSLdapObject(DSLogging): """ try: - self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') except ldap.NO_SUCH_OBJECT: return False @@ -148,7 +148,7 @@ class DSLdapObject(DSLogging): :returns: LDIF formatted string """ - e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return e.__repr__() def display_attr(self, attr): @@ -225,7 +225,7 @@ class DSLdapObject(DSLogging): raise ValueError("Invalid state. Cannot get presence on instance that is not ONLINE") self._log.debug("%s present(%r) %s" % (self._dn, attr, value)) - e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] values = self.get_attr_vals_bytes(attr) self._log.debug("%s contains %s" % (self._dn, values)) @@ -278,7 +278,7 @@ class DSLdapObject(DSLogging): else: value = [ensure_bytes(arg[1])] mods.append((ldap.MOD_REPLACE, ensure_str(arg[0]), value)) - return self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls) + return self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') # This needs to work on key + val, and key def remove(self, key, value): @@ -373,7 +373,7 @@ class DSLdapObject(DSLogging): value = [ensure_bytes(value)] return self._instance.modify_ext_s(self._dn, [(action, key, value)], - serverctrls=self._server_controls, clientctrls=self._client_controls) + serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') def apply_mods(self, mods): """Perform modification operation using several mods at once @@ -411,7 +411,7 @@ class DSLdapObject(DSLogging): else: # Error too many items raise ValueError('Too many arguments in the mod op') - return self._instance.modify_ext_s(self._dn, mod_list, serverctrls=self._server_controls, clientctrls=self._client_controls) + return self._instance.modify_ext_s(self._dn, mod_list, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') @classmethod def compare(cls, obj1, obj2): @@ -478,7 +478,7 @@ class DSLdapObject(DSLogging): raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") else: # retrieving real(*) and operational attributes(+) - attrs_entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*", "+"], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + attrs_entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*", "+"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] # getting dict from 'entry' object attrs_dict = attrs_entry.data return attrs_dict @@ -488,14 +488,14 @@ class DSLdapObject(DSLogging): if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") else: - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return entry.getValuesSet(keys) def get_attrs_vals_utf8(self, keys, use_json=False): self._log.debug("%s get_attrs_vals_utf8(%r)" % (self._dn, keys)) if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] vset = entry.getValuesSet(keys) r = {} for (k, vo) in vset.items(): @@ -513,7 +513,7 @@ class DSLdapObject(DSLogging): else: # It would be good to prevent the entry code intercepting this .... # We have to do this in this method, because else we ignore the scope base. - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] vals = entry.getValues(key) if use_json: result = {key: []} @@ -531,7 +531,7 @@ class DSLdapObject(DSLogging): # In the future, I plan to add a mode where if local == true, we # can use get on dse.ldif to get values offline. else: - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls)[0] + entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return entry.getValue(key) def get_attr_val_bytes(self, key, use_json=False): @@ -659,7 +659,7 @@ class DSLdapObject(DSLogging): # and the superior as the base (if it changed) if self._protected: return - self._instance.rename_s(self._dn, new_rdn, newsuperior, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.rename_s(self._dn, new_rdn, newsuperior, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') search_base = self._basedn if newsuperior != None: # Well, the new DN should be rdn + newsuperior. @@ -681,7 +681,7 @@ class DSLdapObject(DSLogging): self._log.debug("%s delete" % (self._dn)) if not self._protected: # Is there a way to mark this as offline and kill it - self._instance.delete_ext_s(self._dn, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.delete_ext_s(self._dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') def _validate(self, rdn, properties, basedn): """Used to validate a create request. @@ -767,7 +767,7 @@ class DSLdapObject(DSLogging): exists = False try: - self._instance.search_ext_s(dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.search_ext_s(dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') exists = True except ldap.NO_SUCH_OBJECT: pass @@ -780,7 +780,7 @@ class DSLdapObject(DSLogging): mods = [] for k, v in list(valid_props.items()): mods.append((ldap.MOD_REPLACE, k, v)) - self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') elif exists and not ensure: # raise "already exists." raise ldap.ALREADY_EXISTS("Entry %s already exists" % dn) @@ -791,7 +791,7 @@ class DSLdapObject(DSLogging): e.update(valid_props) # We rely on exceptions here to indicate failure to the parent. self._log.debug('Creating entry %s : %s' % (dn, e)) - self._instance.add_ext_s(e, serverctrls=self._server_controls, clientctrls=self._client_controls) + self._instance.add_ext_s(e, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') # If it worked, we need to fix our instance dn self._dn = dn return self @@ -918,7 +918,8 @@ class DSLdapObjects(DSLogging): scope=self._scope, filterstr=filterstr, attrlist=self._list_attrlist, - serverctrls=self._server_controls, clientctrls=self._client_controls + serverctrls=self._server_controls, clientctrls=self._client_controls, + escapehatch='i am sure' ) # def __init__(self, instance, dn=None): insts = [self._entry_to_instance(dn=r.dn, entry=r) for r in results] @@ -966,7 +967,8 @@ class DSLdapObjects(DSLogging): scope=ldap.SCOPE_BASE, filterstr=filterstr, attrlist=self._list_attrlist, - serverctrls=self._server_controls, clientctrls=self._client_controls + serverctrls=self._server_controls, clientctrls=self._client_controls, + escapehatch='i am sure' ) def _get_selector(self, selector): @@ -980,7 +982,8 @@ class DSLdapObjects(DSLogging): scope=self._scope, filterstr=filterstr, attrlist=self._list_attrlist, - serverctrls=self._server_controls, clientctrls=self._client_controls + serverctrls=self._server_controls, clientctrls=self._client_controls, + escapehatch='i am sure' ) def _validate(self, rdn, properties): diff --git a/src/lib389/lib389/idm/account.py b/src/lib389/lib389/idm/account.py index 5dd325bef..729f0b41f 100644 --- a/src/lib389/lib389/idm/account.py +++ b/src/lib389/lib389/idm/account.py @@ -59,7 +59,7 @@ class Account(DSLdapObject): :param password: An entry password :type password: str """ - self._instance.simple_bind_s(self.dn, password) + self._instance.simple_bind_s(self.dn, password, escapehatch='i am sure') def sasl_bind(self, *args, **kwargs): """Open a new connection and bind with the entry via SASL. @@ -140,7 +140,7 @@ class Account(DSLdapObject): # Please see _mapped_object.py and DSLdapObject for why this is structured # in this way re-controls. self._instance.passwd_s(self._dn, current_password, new_password, - serverctrls=self._server_controls, clientctrls=self._client_controls) + serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') class Accounts(DSLdapObjects): """DSLdapObjects that represents Account entry diff --git a/src/lib389/lib389/tasks.py b/src/lib389/lib389/tasks.py index daf397851..8878e5128 100644 --- a/src/lib389/lib389/tasks.py +++ b/src/lib389/lib389/tasks.py @@ -38,11 +38,21 @@ class Task(DSLdapObject): self._protected = False self._exit_code = None + def status(self): + """Return the decoded status of the task + """ + return self.get_attr_val_utf8('nsTaskStatus') + def is_complete(self): """Return True if task is complete, else False.""" - self._exit_code = self.get_attr_val("nsTaskExitCode") - if not self.exists() or self._exit_code is not None: + self._exit_code = self.get_attr_val_utf8("nsTaskExitCode") + if not self.exists(): + self._log.debug("complete: task has self cleaned ...") + # The task cleaned it self up. + return True + elif self._exit_code is not None: + self._log.debug("complete status: %s -> %s" % (self._exit_code, self.status())) return True return False @@ -243,11 +253,24 @@ class ImportTask(Task): def __init__(self, instance, dn=None): self.cn = 'import_' + Task._get_task_date() - dn = "cn=" + self.cn + ",cn=import," + DN_TASKS + dn = "cn=%s,%s" % (self.cn, DN_IMPORT_TASK) self._properties = None super(ImportTask, self).__init__(instance, dn) + # We can add all the needed and valid option combos here. + def import_suffix_from_ldif(self, ldiffile, suffix): + # TODO: Check that the arguments we were given are valid combinations. + # Write out new ones. + _properties = { + 'nsFilename': ldiffile, + 'nsIncludeSuffix': suffix, + } + self.create(properties=_properties) + + # The correlating function would be import_backend_from_ldif which + # would list a bename not suffix + class ExportTask(Task): """Create the export to ldif task @@ -258,11 +281,18 @@ class ExportTask(Task): def __init__(self, instance, dn=None): self.cn = 'export_' + Task._get_task_date() - dn = "cn=" + self.cn + ",cn=export," + DN_TASKS + dn = "cn=%s,%s" % (self.cn, DN_EXPORT_TASK) self._properties = None super(ExportTask, self).__init__(instance, dn) + def export_suffix_to_ldif(self, ldiffile, suffix): + _properties = { + 'nsFilename': ldiffile, + 'nsIncludeSuffix': suffix, + } + self.create(properties=_properties) + class BackupTask(Task): """Create the backup DB task diff --git a/src/lib389/lib389/tombstone.py b/src/lib389/lib389/tombstone.py index 839fc3e3d..527f60127 100644 --- a/src/lib389/lib389/tombstone.py +++ b/src/lib389/lib389/tombstone.py @@ -35,7 +35,7 @@ class Tombstone(DSLdapObject): # We need to always add this filter, else we won't see the ts self._object_filter = '(&(objectclass=nsTombStone)({}))'.format(self._entry_rdn) - def raw_entry(self): + def _unsafe_raw_entry(self): """Get an Entry object :returns: Entry object
0
55a23aa703421013764231a3dfa547c11ef5e2dc
389ds/389-ds-base
609255 - fix coverity Defect Type: Memory - illegal accesses issues https://bugzilla.redhat.com/show_bug.cgi?id=609255 12233 UNINIT Triaged Unassigned Bug Minor Fix Required preop_modify() ds/ldap/servers/plugins/uiduniq/uid.c Comment: This is not an issue since attrName is an output variable for getArguments at the line 689. But to make coverity happy, we init attrName to NULL.
commit 55a23aa703421013764231a3dfa547c11ef5e2dc Author: Noriko Hosoi <[email protected]> Date: Wed Jun 30 10:45:03 2010 -0700 609255 - fix coverity Defect Type: Memory - illegal accesses issues https://bugzilla.redhat.com/show_bug.cgi?id=609255 12233 UNINIT Triaged Unassigned Bug Minor Fix Required preop_modify() ds/ldap/servers/plugins/uiduniq/uid.c Comment: This is not an issue since attrName is an output variable for getArguments at the line 689. But to make coverity happy, we init attrName to NULL. diff --git a/ldap/servers/plugins/uiduniq/uid.c b/ldap/servers/plugins/uiduniq/uid.c index 1464b5276..64b5b1448 100644 --- a/ldap/servers/plugins/uiduniq/uid.c +++ b/ldap/servers/plugins/uiduniq/uid.c @@ -436,7 +436,7 @@ getArguments(Slapi_PBlock *pb, char **attrName, char **markerObjectClass, if (NULL == delimiter) { /* Old style untagged parameter */ - *attrName = *argv; + *attrName = *argv; return UNTAGGED_PARAMETER; } if (strncasecmp(param, "attribute", delimiter-param) == 0) @@ -661,7 +661,7 @@ preop_modify(Slapi_PBlock *pb) BEGIN int err; - char *attrName; + char *attrName = NULL; char *markerObjectClass=NULL; char *requiredObjectClass=NULL; LDAPMod **mods; @@ -806,7 +806,7 @@ preop_modrdn(Slapi_PBlock *pb) BEGIN int err; - char *attrName; + char *attrName = NULL; char *markerObjectClass=NULL; char *requiredObjectClass=NULL; char *dn;
0
c1a89263495c933673f8b977f6c202f34e65b293
389ds/389-ds-base
Bug 609590 - fix coverity Defect Type: Memory - corruptions issues https://bugzilla.redhat.com/show_bug.cgi?id=609590 Resolves: bug 609590 Bug Description: fix coverity Defect Type: Memory - corruptions issues Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: The code is allocating an array of struct dynalib *, so the sizeof needs to use (struct dynalib *) not (struct dynalib). Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no
commit c1a89263495c933673f8b977f6c202f34e65b293 Author: Rich Megginson <[email protected]> Date: Wed Jun 30 14:08:55 2010 -0600 Bug 609590 - fix coverity Defect Type: Memory - corruptions issues https://bugzilla.redhat.com/show_bug.cgi?id=609590 Resolves: bug 609590 Bug Description: fix coverity Defect Type: Memory - corruptions issues Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: The code is allocating an array of struct dynalib *, so the sizeof needs to use (struct dynalib *) not (struct dynalib). Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/dynalib.c b/ldap/servers/slapd/dynalib.c index a659a5e5b..58481a800 100644 --- a/ldap/servers/slapd/dynalib.c +++ b/ldap/servers/slapd/dynalib.c @@ -129,7 +129,7 @@ sym_load_with_flags( char *libpath, char *symbol, char *plugin, int report_error } libs = (struct dynalib **) slapi_ch_realloc( (char *) libs, (i + 2) * - sizeof(struct dynalib) ); + sizeof(struct dynalib *) ); libs[i] = (struct dynalib *) slapi_ch_malloc( sizeof(struct dynalib) ); libs[i]->dl_name = slapi_ch_strdup( libpath ); libs[i]->dl_handle = handle;
0
a8d546760be7b61c0917735bea248114e1dbdcbf
389ds/389-ds-base
[Bug 164834] modify/replace allows multiple same valued attributes in an entry 1) Eliminated SLAPD_MODUTIL_TREE_THREASHHOLD from attr.c as well as valueset.c. With this change, if an attribute has more than 1 value to add/replace/delete, it creates an AVL tree to check the duplicates. 2) Replace was not checking the duplicated value at all. Added a code to put the attribute values into the AVL tree as being done for add and delete.
commit a8d546760be7b61c0917735bea248114e1dbdcbf Author: Noriko Hosoi <[email protected]> Date: Thu Aug 25 00:58:27 2005 +0000 [Bug 164834] modify/replace allows multiple same valued attributes in an entry 1) Eliminated SLAPD_MODUTIL_TREE_THREASHHOLD from attr.c as well as valueset.c. With this change, if an attribute has more than 1 value to add/replace/delete, it creates an AVL tree to check the duplicates. 2) Replace was not checking the duplicated value at all. Added a code to put the attribute values into the AVL tree as being done for add and delete. diff --git a/ldap/servers/slapd/attr.c b/ldap/servers/slapd/attr.c index 9f8c9f960..053cfa6d6 100644 --- a/ldap/servers/slapd/attr.c +++ b/ldap/servers/slapd/attr.c @@ -710,19 +710,12 @@ attr_add_deleted_value(Slapi_Attr *a, const Slapi_Value *v) } /* - * If we are adding or deleting SLAPD_MODUTIL_TREE_THRESHHOLD or more - * entries, we use an AVL tree to speed up searching for duplicates or - * values we are trying to delete. This threshhold is somewhat arbitrary; - * we should really take some measurements to determine an optimal number. - */ -#define SLAPD_MODUTIL_TREE_THRESHHOLD 5 - -/* - * Add a value array to an attribute. If SLAPD_MODUTIL_TREE_THRESHHOLD or - * more values are being added, we build an AVL tree of any existing + * Add a value array to an attribute. + * If more than one values are being added, we build an AVL tree of any existing * values and then update that in parallel with the existing values. This - * is done so that we do not waste a lot of CPU time searching for duplicate - * values. The AVL tree is created and destroyed all within this function. + * AVL tree is used to detect the duplicates not only between the existing + * values and to-be-added values but also among the to-be-added values. + * The AVL tree is created and destroyed all within this function. * * Returns * LDAP_SUCCESS - OK @@ -733,28 +726,28 @@ int attr_add_valuearray(Slapi_Attr *a, Slapi_Value **vals, const char *dn) { int i = 0; - int duplicate_index = -1; - int was_present_null = 0; - int rc = LDAP_SUCCESS; + int numofvals = 0; + int duplicate_index = -1; + int was_present_null = 0; + int rc = LDAP_SUCCESS; if (valuearray_isempty(vals)) { /* * No values to add (unexpected but acceptable). */ return rc; - } + } /* * determine whether we should use an AVL tree of values or not */ - while ( i < SLAPD_MODUTIL_TREE_THRESHHOLD - 1 && vals[i] != NULL ) { - i++; - } + for ( i = 0; vals[i] != NULL; i++ ) ; + numofvals = i; /* * detect duplicate values */ - if ( i >= SLAPD_MODUTIL_TREE_THRESHHOLD - 1 ) { + if ( numofvals > 1 ) { /* * Several values to add: use an AVL tree to detect duplicates. */ @@ -763,82 +756,85 @@ attr_add_valuearray(Slapi_Attr *a, Slapi_Value **vals, const char *dn) "detect duplicate values\n", 0, 0, 0 ); if (valueset_isempty(&a->a_present_values)) { - /* if the attribute contains no values yet, just check the - * input vals array for duplicates - */ + /* if the attribute contains no values yet, just check the + * input vals array for duplicates + */ Avlnode *vtree = NULL; rc= valuetree_add_valuearray(a->a_type, a->a_plugin, vals, &vtree, &duplicate_index); valuetree_free(&vtree); - was_present_null = 1; + was_present_null = 1; } else { - /* the attr and vals both contain values, check intersection */ + /* the attr and vals both contain values, check intersection */ rc= valueset_intersectswith_valuearray(&a->a_present_values, a, vals, &duplicate_index); } } else if ( !valueset_isempty(&a->a_present_values) ) { /* - * Small number of values to add: don't bother constructing + * One or no value to add: don't bother constructing * an AVL tree, etc. since it probably isn't worth the time. */ for ( i = 0; vals[i] != NULL; ++i ) { if ( slapi_attr_value_find( a, slapi_value_get_berval(vals[i]) ) == 0 ) { - duplicate_index = i; - rc = LDAP_TYPE_OR_VALUE_EXISTS; - break; + duplicate_index = i; + rc = LDAP_TYPE_OR_VALUE_EXISTS; + break; } - } + } } - /* - * add values if no duplicates detected - */ + /* + * add values if no duplicates detected + */ if(rc==LDAP_SUCCESS) { - valueset_add_valuearray( &a->a_present_values, vals ); - } + valueset_add_valuearray( &a->a_present_values, vals ); + } - /* In the case of duplicate value, rc == LDAP_TYPE_OR_VALUE_EXISTS or - * LDAP_OPERATIONS_ERROR - */ - else if ( duplicate_index >= 0 ) { - char avdbuf[BUFSIZ]; - char bvvalcopy[BUFSIZ]; - char *duplicate_string = "null or non-ASCII"; - - i = 0; - while ( (unsigned int)i < vals[duplicate_index]->bv.bv_len && - i < BUFSIZ - 1 && - vals[duplicate_index]->bv.bv_val[i] && - isascii ( vals[duplicate_index]->bv.bv_val[i] )) { - i++; - } + /* In the case of duplicate value, rc == LDAP_TYPE_OR_VALUE_EXISTS or + * LDAP_OPERATIONS_ERROR + */ + else if ( duplicate_index >= 0 ) { + char avdbuf[BUFSIZ]; + char bvvalcopy[BUFSIZ]; + char *duplicate_string = "null or non-ASCII"; + + i = 0; + while ( (unsigned int)i < vals[duplicate_index]->bv.bv_len && + i < BUFSIZ - 1 && + vals[duplicate_index]->bv.bv_val[i] && + isascii ( vals[duplicate_index]->bv.bv_val[i] )) { + i++; + } - if ( i ) { - if ( vals[duplicate_index]->bv.bv_val[i] == 0 ) { - duplicate_string = vals[duplicate_index]->bv.bv_val; - } - else { - strncpy ( &bvvalcopy[0], vals[duplicate_index]->bv.bv_val, i ); - bvvalcopy[i] = '\0'; - duplicate_string = bvvalcopy; - } - } + if ( i ) { + if ( vals[duplicate_index]->bv.bv_val[i] == 0 ) { + duplicate_string = vals[duplicate_index]->bv.bv_val; + } + else { + strncpy ( &bvvalcopy[0], vals[duplicate_index]->bv.bv_val, i ); + bvvalcopy[i] = '\0'; + duplicate_string = bvvalcopy; + } + } - slapi_log_error( SLAPI_LOG_FATAL, NULL, "add value \"%s\" to " - "attribute type \"%s\" in entry \"%s\" failed: %s\n", - duplicate_string, - a->a_type, - dn ? escape_string(dn,avdbuf) : "<null>", - (was_present_null ? "duplicate new value" : "value exists")); - } + slapi_log_error( SLAPI_LOG_FATAL, NULL, "add value \"%s\" to " + "attribute type \"%s\" in entry \"%s\" failed: %s\n", + duplicate_string, + a->a_type, + dn ? escape_string(dn,avdbuf) : "<null>", + (was_present_null ? "duplicate new value" : "value exists")); + } return( rc ); } /* quickly toss an attribute's values and replace them with new ones * (used by attrlist_replace_fast) + * Returns + * LDAP_SUCCESS - OK + * LDAP_OPERATIONS_ERROR - Existing duplicates in attribute. */ -void attr_replace(Slapi_Attr *a, Slapi_Value **vals) +int attr_replace(Slapi_Attr *a, Slapi_Value **vals) { - valueset_replace(&a->a_present_values, vals); + return valueset_replace(a, &a->a_present_values, vals); } int diff --git a/ldap/servers/slapd/attrlist.c b/ldap/servers/slapd/attrlist.c index 8fd89fcbd..eacdb3d4b 100644 --- a/ldap/servers/slapd/attrlist.c +++ b/ldap/servers/slapd/attrlist.c @@ -268,18 +268,24 @@ attrlist_delete(Slapi_Attr **attrs, const char *type) /* * attrlist_replace - replace the attribute value(s) with this value(s) + * + * Returns + * LDAP_SUCCESS - OK (including the attr not found) + * LDAP_OPERATIONS_ERROR - Existing duplicates in attribute. */ -void attrlist_replace(Slapi_Attr **alist, const char *type, struct berval **vals) +int attrlist_replace(Slapi_Attr **alist, const char *type, struct berval **vals) { Slapi_Attr **a = NULL; Slapi_Value **values = NULL; + int rc = LDAP_SUCCESS; if (vals == NULL || vals[0] == NULL) { (void)attrlist_delete(alist, type); } else { attrlist_find_or_create(alist, type, &a); valuearray_init_bervalarray(vals, &values); - attr_replace(*a, values); + rc = attr_replace(*a, values); } + return rc; } diff --git a/ldap/servers/slapd/entry.c b/ldap/servers/slapd/entry.c index bf89542ce..cd5010b69 100644 --- a/ldap/servers/slapd/entry.c +++ b/ldap/servers/slapd/entry.c @@ -2792,8 +2792,7 @@ entry_replace_values( struct berval **vals ) { - attrlist_replace( &e->e_attrs, type, vals ); - return 0; + return attrlist_replace( &e->e_attrs, type, vals ); } int diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 5f37b9200..a40dd3cd6 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -61,7 +61,7 @@ void do_add( Slapi_PBlock *pb ); */ void attr_done(Slapi_Attr *a); int attr_add_valuearray(Slapi_Attr *a, Slapi_Value **vals, const char *dn); -void attr_replace(Slapi_Attr *a, Slapi_Value **vals); +int attr_replace(Slapi_Attr *a, Slapi_Value **vals); int attr_check_onoff ( const char *attr_name, char *value, long minval, long maxval, char *errorbuf ); int attr_check_minmax ( const char *attr_name, char *value, long minval, long maxval, char *errorbuf ); @@ -80,7 +80,7 @@ Slapi_Attr *attrlist_remove(Slapi_Attr **attrs, const char *type); void attrlist_add(Slapi_Attr **attrs, Slapi_Attr *a); int attrlist_count_subtypes(Slapi_Attr *a, const char *type); Slapi_Attr *attrlist_find_ex( Slapi_Attr *a, const char *type, int *type_name_disposition, char** actual_type_name, void **hint ); -void attrlist_replace(Slapi_Attr **alist, const char *type, struct berval **vals); +int attrlist_replace(Slapi_Attr **alist, const char *type, struct berval **vals); /* * attrsyntax.c @@ -158,7 +158,7 @@ void valueset_add_valueset(Slapi_ValueSet *vs1, const Slapi_ValueSet *vs2); int valueset_intersectswith_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slapi_Value **values, int *duplicate_index); Slapi_ValueSet *valueset_dup(const Slapi_ValueSet *dupee); void valueset_remove_string(const Slapi_Attr *a, Slapi_ValueSet *vs, const char *s); -void valueset_replace(Slapi_ValueSet *vs, Slapi_Value **vals); +int valueset_replace(Slapi_Attr *a, Slapi_ValueSet *vs, Slapi_Value **vals); void valueset_update_csn_for_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slapi_Value **valuestoupdate, CSNType t, const CSN *csn, Slapi_Value ***valuesupdated); void valueset_set_valuearray_byval(Slapi_ValueSet *vs, Slapi_Value **addvals); void valueset_set_valuearray_passin(Slapi_ValueSet *vs, Slapi_Value **addvals); diff --git a/ldap/servers/slapd/valueset.c b/ldap/servers/slapd/valueset.c index a65cbdd2e..653591dce 100644 --- a/ldap/servers/slapd/valueset.c +++ b/ldap/servers/slapd/valueset.c @@ -1014,13 +1014,6 @@ valueset_update_csn(Slapi_ValueSet *vs, CSNType t, const CSN *csn) } } -/* - * If we are adding or deleting SLAPD_MODUTIL_TREE_THRESHHOLD or more - * entries, we use an AVL tree to speed up searching for duplicates or - * values we are trying to delete. This threshhold is somewhat arbitrary; - * we should really take some measurements to determine an optimal number. - */ -#define SLAPD_MODUTIL_TREE_THRESHHOLD 5 /* * Remove an array of values from a value set. * The removed values are passed back in an array. @@ -1044,9 +1037,10 @@ valueset_remove_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slapi_Value } /* - * determine whether we should use an AVL tree of values or not + * If there are more then one values, build an AVL tree to check + * the duplicated values. */ - if ( numberofvaluestodelete >= SLAPD_MODUTIL_TREE_THRESHHOLD) + if ( numberofvaluestodelete > 1 ) { /* * Several values to delete: first build an AVL tree that @@ -1132,7 +1126,7 @@ valueset_remove_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slapi_Value } else { - /* We don't have to delete very many values, so we use brute force. */ + /* We delete one or no value, so we use brute force. */ int i; for ( i = 0; rc==LDAP_SUCCESS && valuestodelete[i] != NULL; ++i ) { @@ -1210,7 +1204,7 @@ valueset_intersectswith_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slap { /* No intersection */ } - else if ( numberofvalues >= SLAPD_MODUTIL_TREE_THRESHHOLD) + else if ( numberofvalues > 1 ) { /* * Several values to add: use an AVL tree to detect duplicates. @@ -1234,7 +1228,7 @@ valueset_intersectswith_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slap else { /* - * Small number of values to add: don't bother constructing + * One value to add: don't bother constructing * an AVL tree, etc. since it probably isn't worth the time. * * JCM - This is actually quite slow because the comparison function is looked up many times. @@ -1267,15 +1261,39 @@ valueset_dup(const Slapi_ValueSet *dupee) /* quickly throw away any old contents of this valueset, and stick in the * new ones. + * + * return value: LDAP_SUCCESS - OK + * : LDAP_OPERATIONS_ERROR - duplicated values given */ -void -valueset_replace(Slapi_ValueSet *vs, Slapi_Value **vals) +int +valueset_replace(Slapi_Attr *a, Slapi_ValueSet *vs, Slapi_Value **valstoreplace) { + int rc = LDAP_SUCCESS; + int numberofvalstoreplace= valuearray_count(valstoreplace); if(!valuearray_isempty(vs->va)) - { + { slapi_valueset_done(vs); - } - vs->va = vals; + } + /* verify the given values are not duplicated. + if replacing with one value, no need to check. just replace it. + */ + if (numberofvalstoreplace > 1) + { + Avlnode *vtree = NULL; + rc = valuetree_add_valuearray( a->a_type, a->a_plugin, valstoreplace, &vtree, NULL ); + valuetree_free(&vtree); + if ( LDAP_SUCCESS != rc ) + { + /* There were already duplicate values in the value set */ + rc = LDAP_OPERATIONS_ERROR; + } + } + + if ( rc == LDAP_SUCCESS ) + { + vs->va = valstoreplace; + } + return rc; } /* @@ -1296,7 +1314,7 @@ valueset_update_csn_for_valuearray(Slapi_ValueSet *vs, const Slapi_Attr *a, Slap struct valuearrayfast vaf_valuesupdated; int numberofvaluestoupdate= valuearray_count(valuestoupdate); valuearrayfast_init(&vaf_valuesupdated,*valuesupdated); - if (numberofvaluestoupdate>=SLAPD_MODUTIL_TREE_THRESHHOLD) + if (numberofvaluestoupdate > 1) /* multiple values to update */ { int i; Avlnode *vtree = NULL;
0
15789e895c4b976774dc3cb3ba5e64f23bcd8c3b
389ds/389-ds-base
Issue 49761 - Fix CI test suite issues Description: Fix various test issues on RHEL7 and RHEL8: * systemd on RHEL7 doesn't have --value option. Drop --value option and parse the output manually. * Use newer BDB config only on 1.4.2+. * Skip tests/suites/password/pbkdf2_upgrade_plugin_test.py on <1.4.1. * Unhashed passwords are not logged by default only on 1.4.1.6+. * String literal comparison doesn't work with double digits, i.e. '1.3.10.1' > '1.3.2.1' returns False. Use packaging.version to compare versions. * Don't use nsAccount objectClass on versions <=1.4.x. * Update skipif/xfail version to match downstream versions too. Relates: https://pagure.io/389-ds-base/issue/49761 Reviewed by: firstyear (Thanks!)
commit 15789e895c4b976774dc3cb3ba5e64f23bcd8c3b Author: Viktor Ashirov <[email protected]> Date: Fri Nov 1 12:55:55 2019 +0100 Issue 49761 - Fix CI test suite issues Description: Fix various test issues on RHEL7 and RHEL8: * systemd on RHEL7 doesn't have --value option. Drop --value option and parse the output manually. * Use newer BDB config only on 1.4.2+. * Skip tests/suites/password/pbkdf2_upgrade_plugin_test.py on <1.4.1. * Unhashed passwords are not logged by default only on 1.4.1.6+. * String literal comparison doesn't work with double digits, i.e. '1.3.10.1' > '1.3.2.1' returns False. Use packaging.version to compare versions. * Don't use nsAccount objectClass on versions <=1.4.x. * Update skipif/xfail version to match downstream versions too. Relates: https://pagure.io/389-ds-base/issue/49761 Reviewed by: firstyear (Thanks!) diff --git a/dirsrvtests/tests/suites/automember_plugin/basic_test.py b/dirsrvtests/tests/suites/automember_plugin/basic_test.py index 1fd34f525..d9bfe7cab 100644 --- a/dirsrvtests/tests/suites/automember_plugin/basic_test.py +++ b/dirsrvtests/tests/suites/automember_plugin/basic_test.py @@ -11,6 +11,8 @@ Will test AutoMememer Plugin with AotoMember Task and Retro Changelog """ import os +import ldap +import pytest from lib389.topologies import topology_m1 as topo from lib389.idm.organizationalunit import OrganizationalUnits from lib389.idm.domain import Domain @@ -20,9 +22,8 @@ from lib389.plugins import AutoMembershipPlugin, AutoMembershipDefinitions, \ from lib389.backend import Backends from lib389.config import Config from lib389._constants import DEFAULT_SUFFIX -import ldap -import pytest from lib389.idm.group import Groups, Group, UniqueGroup, nsAdminGroups, nsAdminGroup +from lib389.utils import ds_is_older pytestmark = pytest.mark.tier1 @@ -72,6 +73,11 @@ def add_user(topo, user_id, suffix, uid_no, gid_no, role_usr): """ Will create entries with nsAdminGroup objectclass """ + objectclasses = ['top', 'person', 'posixaccount', 'inetuser', + 'nsMemberOf', 'nsAccount', 'nsAdminGroup'] + if ds_is_older('1.4.0'): + objectclasses.remove('nsAccount') + user = nsAdminGroups(topo.ms["master1"], suffix, rdn=None).create(properties={ 'cn': user_id, 'sn': user_id, @@ -80,8 +86,7 @@ def add_user(topo, user_id, suffix, uid_no, gid_no, role_usr): 'loginShell': '/bin/bash', 'uidNumber': uid_no, 'gidNumber': gid_no, - 'objectclass': ['top', 'person', 'posixaccount', 'inetuser', - 'nsMemberOf', 'nsAccount', 'nsAdminGroup'], + 'objectclass': objectclasses, 'nsAdminGroupName': role_usr, 'seeAlso': 'uid={},{}'.format(user_id, suffix), 'entrydn': 'uid={},{}'.format(user_id, suffix) diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index b1edfd21b..156e2054d 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -624,7 +624,7 @@ search_params = [(['1.1'], 'cn', False), (['+'], 'nsUniqueId', True), (['*'], 'cn', True), (['cn'], 'cn', True)] [email protected](ds_is_older("1.4.1.6"), reason="Not implemented") [email protected](ds_is_older("1.4.2.0"), reason="Not implemented") @pytest.mark.parametrize("attrs, attr, present", search_params) def test_search_req_attrs(topology_st, add_test_entry, attrs, attr, present): """Test requested attributes in search operations. @@ -1355,7 +1355,7 @@ sample_entries = yes return inst [email protected](not get_user_is_root() or not default_paths.perl_enabled or ds_is_older('1.4.0.0'), [email protected](not get_user_is_root() or not default_paths.perl_enabled or ds_is_older('1.4.2.0'), reason="This test is only required with new admin cli, and requires root.") @pytest.mark.bz1748016 @pytest.mark.ds50581 diff --git a/dirsrvtests/tests/suites/config/autotuning_test.py b/dirsrvtests/tests/suites/config/autotuning_test.py index f27d0ea4f..f40046edf 100644 --- a/dirsrvtests/tests/suites/config/autotuning_test.py +++ b/dirsrvtests/tests/suites/config/autotuning_test.py @@ -124,11 +124,17 @@ def test_cache_autosize_non_zero(topo, autosize, autosize_split): cachesize = '33333333' - dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + if ds_is_older('1.4.2'): + dbcachesize_val = config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + else: + dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + cachenensize_val = userroot_ldbm.get_attr_val('nsslapd-cachememsize') dncachenensize_val = userroot_ldbm.get_attr_val('nsslapd-dncachememsize') - autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') - autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') log.info("Check nsslapd-dbcachesize and nsslapd-cachememsize before the test") log.info("nsslapd-dbcachesize == {}".format(dbcachesize_val)) @@ -165,11 +171,17 @@ def test_cache_autosize_non_zero(topo, autosize, autosize_split): config_ldbm.set('nsslapd-dbcachesize ', cachesize) topo.standalone.restart() - dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + if ds_is_older('1.4.2'): + dbcachesize_val = config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + else: + dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + cachenensize_val = userroot_ldbm.get_attr_val('nsslapd-cachememsize') dncachenensize_val = userroot_ldbm.get_attr_val('nsslapd-dncachememsize') - autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') - autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') log.info("Check nsslapd-dbcachesize and nsslapd-cachememsize in the appropriate range.") log.info("nsslapd-dbcachesize == {}".format(dbcachesize_val)) @@ -215,11 +227,17 @@ def test_cache_autosize_basic_sane(topo, autosize_split): # Test with caches with both real values and 0 for cachesize in ('0', '33333333'): - dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + if ds_is_older('1.4.2'): + dbcachesize_val = config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + else: + dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + cachenensize_val = userroot_ldbm.get_attr_val('nsslapd-cachememsize') dncachenensize_val = userroot_ldbm.get_attr_val('nsslapd-dncachememsize') - autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') - autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') log.info("Check nsslapd-dbcachesize and nsslapd-cachememsize before the test") log.info("nsslapd-dbcachesize == {}".format(dbcachesize_val)) @@ -243,11 +261,17 @@ def test_cache_autosize_basic_sane(topo, autosize_split): userroot_ldbm.set('nsslapd-cachememsize', cachesize) topo.standalone.restart() - dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + if ds_is_older('1.4.2'): + dbcachesize_val = config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + else: + dbcachesize_val = bdb_config_ldbm.get_attr_val('nsslapd-dbcachesize') + autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + cachenensize_val = userroot_ldbm.get_attr_val('nsslapd-cachememsize') dncachenensize_val = userroot_ldbm.get_attr_val('nsslapd-dncachememsize') - autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') - autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') log.info("Check nsslapd-dbcachesize and nsslapd-cachememsize in the appropriate range.") log.info("nsslapd-dbcachesize == {}".format(dbcachesize_val)) @@ -280,8 +304,12 @@ def test_cache_autosize_invalid_values(topo, invalid_value): config_ldbm = DSLdapObject(topo.standalone, DN_CONFIG_LDBM) bdb_config_ldbm = DSLdapObject(topo.standalone, DN_CONFIG_LDBM_BDB) - autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') - autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + if ds_is_older('1.4.2'): + autosize_val = config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = config_ldbm.get_attr_val('nsslapd-cache-autosize-split') + else: + autosize_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize') + autosize_split_val = bdb_config_ldbm.get_attr_val('nsslapd-cache-autosize-split') log.info("Set nsslapd-cache-autosize-split to {}".format(invalid_value)) with pytest.raises(ldap.UNWILLING_TO_PERFORM): diff --git a/dirsrvtests/tests/suites/config/config_test.py b/dirsrvtests/tests/suites/config/config_test.py index e9e5bf31f..02c767b04 100644 --- a/dirsrvtests/tests/suites/config/config_test.py +++ b/dirsrvtests/tests/suites/config/config_test.py @@ -146,13 +146,21 @@ def test_config_deadlock_policy(topology_m2): ldbmconfig = LDBMConfig(topology_m2.ms["master1"]) bdbconfig = BDB_LDBMConfig(topology_m2.ms["master1"]) - deadlock_policy = bdbconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + if ds_is_older('1.4.2'): + deadlock_policy = ldbmconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + else: + deadlock_policy = bdbconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + assert deadlock_policy == default_val # Try a range of valid values for val in (b'0', b'5', b'9'): ldbmconfig.replace('nsslapd-db-deadlock-policy', val) - deadlock_policy = bdbconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + if ds_is_older('1.4.2'): + deadlock_policy = ldbmconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + else: + deadlock_policy = bdbconfig.get_attr_val_bytes('nsslapd-db-deadlock-policy') + assert deadlock_policy == val # Try a range of invalid values diff --git a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py index c8f7ef0d5..31e984a55 100644 --- a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py +++ b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py @@ -641,7 +641,7 @@ def test_internal_log_level_516(topology_st, add_user_log_level_516): assert topo.ds_access_log.match(r'.*conn=Internal\([0-9]+\) op=[0-9]+\([0-9]+\)\([0-9]+\).*') [email protected](ds_is_older('1.4.1.4'), reason="Not implemented") [email protected](ds_is_older('1.4.2.0'), reason="Not implemented") @pytest.mark.bz1358706 @pytest.mark.ds49232 def test_access_log_truncated_search_message(topology_st, clean_access_logs): @@ -678,7 +678,7 @@ def test_access_log_truncated_search_message(topology_st, clean_access_logs): [email protected](ds_is_older('1.4.1.6'), reason="May fail because of bug 1732053") [email protected](ds_is_older('1.4.2.0'), reason="May fail because of bug 1732053") @pytest.mark.bz1732053 @pytest.mark.ds50510 def test_etime_at_border_of_second(topology_st, clean_access_logs): diff --git a/dirsrvtests/tests/suites/mapping_tree/referral_during_tot_init_test.py b/dirsrvtests/tests/suites/mapping_tree/referral_during_tot_init_test.py index a29b33f9d..24a085553 100644 --- a/dirsrvtests/tests/suites/mapping_tree/referral_during_tot_init_test.py +++ b/dirsrvtests/tests/suites/mapping_tree/referral_during_tot_init_test.py @@ -18,6 +18,7 @@ from lib389.dbgen import dbgen pytestmark = pytest.mark.tier1 [email protected](ds_is_older("1.4.0.0"), reason="Not implemented") def test_referral_during_tot(topology_m2): master1 = topology_m2.ms["master1"] diff --git a/dirsrvtests/tests/suites/password/pbkdf2_upgrade_plugin_test.py b/dirsrvtests/tests/suites/password/pbkdf2_upgrade_plugin_test.py index ca69fb483..90dae36ec 100644 --- a/dirsrvtests/tests/suites/password/pbkdf2_upgrade_plugin_test.py +++ b/dirsrvtests/tests/suites/password/pbkdf2_upgrade_plugin_test.py @@ -9,9 +9,11 @@ import pytest from lib389.topologies import topology_st from lib389.password_plugins import PBKDF2Plugin +from lib389.utils import ds_is_older pytestmark = pytest.mark.tier1 [email protected](ds_is_older('1.4.1'), reason="Not implemented") def test_pbkdf2_upgrade(topology_st): """On upgrade pbkdf2 doesn't ship. We need to be able to provide this on upgrade to make sure default hashes work. diff --git a/dirsrvtests/tests/suites/password/regression_test.py b/dirsrvtests/tests/suites/password/regression_test.py index c239799e4..93570f9db 100644 --- a/dirsrvtests/tests/suites/password/regression_test.py +++ b/dirsrvtests/tests/suites/password/regression_test.py @@ -12,7 +12,7 @@ from lib389._constants import SUFFIX, PASSWORD, DN_DM, DN_CONFIG, PLUGIN_RETRO_C from lib389 import Entry from lib389.topologies import topology_m1 as topo_master from lib389.idm.user import UserAccounts -from lib389.utils import ldap, os, logging, ensure_bytes +from lib389.utils import ldap, os, logging, ensure_bytes, ds_is_newer from lib389.topologies import topology_st as topo from lib389.idm.organizationalunit import OrganizationalUnits @@ -40,7 +40,7 @@ TEST_PASSWORDS2 = ( 'CN12pwtest31', 'SN3pwtest231', 'UID1pwtest123', '[email protected]', '2GN1pwtest123', 'People123') def _check_unhashed_userpw(inst, user_dn, is_present=False): - """Check if unhashed#user#password attribute is present of not in the changelog""" + """Check if unhashed#user#password attribute is present or not in the changelog""" unhashed_pwd_attribute = 'unhashed#user#password' changelog_dbdir = os.path.join(os.path.dirname(inst.dbdir), DEFAULT_CHANGELOG_DB) @@ -274,13 +274,16 @@ def test_unhashed_pw_switch(topo_master): log.fatal('Failed to add user (%s): error %s' % (USER_DN, e.message['desc'])) assert False - # Check default is that unhashed#user#password is not logged + # Check default is that unhashed#user#password is not logged on 1.4.1.6+ user = "uid=member1,%s" % (PEOPLE_DN) inst.modify_s(user, [(ldap.MOD_REPLACE, 'userpassword', PASSWORD.encode())]) inst.stop() - _check_unhashed_userpw(inst, user, is_present=False) + if ds_is_newer('1.4.1.6'): + _check_unhashed_userpw(inst, user, is_present=False) + else: + _check_unhashed_userpw(inst, user, is_present=True) # Check with nolog that unhashed#user#password is not logged inst.modify_s(DN_CONFIG, diff --git a/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py b/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py index bd2b1e79a..1a2f54734 100644 --- a/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py +++ b/dirsrvtests/tests/suites/resource_limits/fdlimits_test.py @@ -15,7 +15,7 @@ log = logging.getLogger(__name__) FD_ATTR = "nsslapd-maxdescriptors" GLOBAL_LIMIT = resource.getrlimit(resource.RLIMIT_NOFILE)[1] -SYSTEMD_LIMIT = ensure_str(check_output("systemctl show --value -p LimitNOFILE dirsrv@standalone1".split(" ")).strip()) +SYSTEMD_LIMIT = ensure_str(check_output("systemctl show -p LimitNOFILE dirsrv@standalone1".split(" ")).strip()).split('=')[1] CUSTOM_VAL = str(int(SYSTEMD_LIMIT) - 10) TOO_HIGH_VAL = str(GLOBAL_LIMIT * 2) TOO_HIGH_VAL2 = str(int(SYSTEMD_LIMIT) * 2) diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index c271d865e..e817468b5 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -39,6 +39,7 @@ import six import shlex import operator import subprocess +from packaging import version from socket import getfqdn from ldapurl import LDAPUrl from contextlib import closing @@ -1075,9 +1076,9 @@ def ds_is_related(relation, *ver): if len(ver) > 1: for cmp_ver in ver: if cmp_ver.startswith(ds_ver[:3]): - return ops[relation](ds_ver,cmp_ver) + return ops[relation](version.parse(ds_ver),version.parse(cmp_ver)) else: - return ops[relation](ds_ver, ver[0]) + return ops[relation](version.parse(ds_ver), version.parse(ver[0])) def ds_is_older(*ver):
0
4d89e11494233d8297896540bc752cfdbab2cc69
389ds/389-ds-base
Issue 5126 - Memory leak in slapi_ldap_get_lderrno (#5153) * Issue 5126 - Memory leak in slapi_ldap_get_lderrno The problem is that some time ago libldap API replaced ​LDAP_OPT_ERROR_STRING whose data should not be freed by LDAP_OPT_DIAGNOSTIC_MESSAGE whose data must be freed. slapi_ldap_get_lderrno was adapted to use the new option but the callers were not modified to free the value. The Solution: Insure that we also need to free slapi_ldap_get_lderrno value if legacy LDAP_OPT_ERROR_STRING is used (by duping the value) Insure that the callers free the value. Added test case about replication using SASL/Digest-md5 authentication Added test case to check this leak Also updated test case about SASL/GSSAPI to be comapatible with current lib389 framework but marked as skipped because it requires a specific configuration (This path should be tested by IPA tests) Fixed valgrind lib389 function to run on prefixed installation without needing to be root. At last I also improved lib389 mapped object to have a better diagnostic when LDAP operation fails (by adding the request within the exception) issue: 5126 https://github.com/389ds/389-ds-base/issues/5126 Reviewd by: @droideck
commit 4d89e11494233d8297896540bc752cfdbab2cc69 Author: progier389 <[email protected]> Date: Mon May 2 18:43:25 2022 +0200 Issue 5126 - Memory leak in slapi_ldap_get_lderrno (#5153) * Issue 5126 - Memory leak in slapi_ldap_get_lderrno The problem is that some time ago libldap API replaced ​LDAP_OPT_ERROR_STRING whose data should not be freed by LDAP_OPT_DIAGNOSTIC_MESSAGE whose data must be freed. slapi_ldap_get_lderrno was adapted to use the new option but the callers were not modified to free the value. The Solution: Insure that we also need to free slapi_ldap_get_lderrno value if legacy LDAP_OPT_ERROR_STRING is used (by duping the value) Insure that the callers free the value. Added test case about replication using SASL/Digest-md5 authentication Added test case to check this leak Also updated test case about SASL/GSSAPI to be comapatible with current lib389 framework but marked as skipped because it requires a specific configuration (This path should be tested by IPA tests) Fixed valgrind lib389 function to run on prefixed installation without needing to be root. At last I also improved lib389 mapped object to have a better diagnostic when LDAP operation fails (by adding the request within the exception) issue: 5126 https://github.com/389ds/389-ds-base/issues/5126 Reviewd by: @droideck diff --git a/dirsrvtests/tests/suites/gssapi_repl/gssapi_repl_test.py b/dirsrvtests/tests/suites/gssapi_repl/gssapi_repl_test.py index 41f323c06..402684aab 100644 --- a/dirsrvtests/tests/suites/gssapi_repl/gssapi_repl_test.py +++ b/dirsrvtests/tests/suites/gssapi_repl/gssapi_repl_test.py @@ -9,6 +9,7 @@ import pytest from lib389.tasks import * from lib389.utils import * +from lib389.agreement import * from lib389.topologies import topology_m2 pytestmark = pytest.mark.tier2 @@ -65,10 +66,27 @@ def _allow_machine_account(inst, name): # First we need to get the mapping tree dn mt = inst.mappingtree.list(suffix=DEFAULT_SUFFIX)[0] inst.modify_s('cn=replica,%s' % mt.dn, [ - (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDN', "uid=%s,ou=Machines,%s" % (name, DEFAULT_SUFFIX)) + (ldap.MOD_REPLACE, 'nsDS5ReplicaBindDN', f"uid={name},ou=Machines,{DEFAULT_SUFFIX}".encode('utf-8')) ]) - +def _verify_etc_hosts(): + #Check if /etc/hosts is compatible with the test + NEEDED_HOSTS = ( ('ldapkdc.example.com', '127.0.0.1'), + ('ldapkdc1.example.com', '127.0.1.1'), + ('ldapkdc2.example.com', '127.0.2.1')) + found_hosts = {} + with open('/etc/hosts','r') as f: + for l in f: + s = l.split() + if len(s) < 2: + continue + for nh in NEEDED_HOSTS: + if (s[0] == nh[1] and s[1] == nh[0]): + found_hosts[s[1]] = True + return len(found_hosts) == len(NEEDED_HOSTS) + [email protected](not _verify_etc_hosts(), reason="/etc/hosts does not contains the needed hosts.") [email protected](True, reason="Test disabled because it requires specific kerberos requirement (server principal, keytab, etc ...") def test_gssapi_repl(topology_m2): """Test gssapi authenticated replication agreement of two suppliers using KDC @@ -94,8 +112,6 @@ def test_gssapi_repl(topology_m2): 6. Test User should be created on M1 and M2 both 7. Test User should be created on M1 and M2 both """ - - return supplier1 = topology_m2.ms["supplier1"] supplier2 = topology_m2.ms["supplier2"] @@ -121,6 +137,7 @@ def test_gssapi_repl(topology_m2): properties = {RA_NAME: r'meTo_$host:$port', RA_METHOD: 'SASL/GSSAPI', RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} + supplier1.agreement.delete(suffix=SUFFIX, consumer_host=supplier2.host, consumer_port=supplier2.port) m1_m2_agmt = supplier1.agreement.create(suffix=SUFFIX, host=supplier2.host, port=supplier2.port, properties=properties) if not m1_m2_agmt: log.fatal("Fail to create a supplier -> supplier replica agreement") @@ -133,6 +150,7 @@ def test_gssapi_repl(topology_m2): properties = {RA_NAME: r'meTo_$host:$port', RA_METHOD: 'SASL/GSSAPI', RA_TRANSPORT_PROT: defaultProperties[REPLICATION_TRANSPORT]} + supplier2.agreement.delete(suffix=SUFFIX, consumer_host=supplier1.host, consumer_port=supplier1.port) m2_m1_agmt = supplier2.agreement.create(suffix=SUFFIX, host=supplier1.host, port=supplier1.port, properties=properties) if not m2_m1_agmt: log.fatal("Fail to create a supplier -> supplier replica agreement") @@ -145,8 +163,9 @@ def test_gssapi_repl(topology_m2): # # Initialize all the agreements # - supplier1.agreement.init(SUFFIX, HOST_SUPPLIER_2, PORT_SUPPLIER_2) - supplier1.waitForReplInit(m1_m2_agmt) + agmt = Agreement(supplier1, m1_m2_agmt) + agmt.begin_reinit() + agmt.wait_reinit() # Check replication is working... if supplier1.testReplication(DEFAULT_SUFFIX, supplier2): diff --git a/dirsrvtests/tests/suites/replication/sasl_m2_test.py b/dirsrvtests/tests/suites/replication/sasl_m2_test.py new file mode 100644 index 000000000..d7406ac7e --- /dev/null +++ b/dirsrvtests/tests/suites/replication/sasl_m2_test.py @@ -0,0 +1,185 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2022 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import logging +import os +import pytest +import ldap +import uuid +from lib389.utils import ds_is_older, valgrind_enable, valgrind_disable, valgrind_get_results_file, valgrind_check_file + +from lib389.idm.services import ServiceAccounts +from lib389.idm.group import Groups +from lib389.config import CertmapLegacy, Config +from lib389._constants import DEFAULT_SUFFIX +from lib389.agreement import Agreements +from lib389._mapped_object import DSLdapObject +from lib389.replica import ReplicationManager, Replicas, BootstrapReplicationManager +from lib389.topologies import topology_m2 as topo_m2 + +pytestmark = pytest.mark.tier1 + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + +def set_sasl_md5_client_auth(inst, to): + # Create the certmap before we restart + cm = CertmapLegacy(to) + certmaps = cm.list() + certmaps['default']['nsSaslMapRegexString'] = '^dn:\\(.*\\)' + certmaps['default']['nsSaslMapBaseDNTemplate'] = 'cn=config' + certmaps['default']['nsSaslMapFilterTemplate'] = '(objectclass=*)' + cm.set(certmaps) + + Config(to).replace("passwordStorageScheme", 'CLEAR') + + # Create a repl manager on the replica + replication_manager_pwd = 'secret12' + brm = BootstrapReplicationManager(to) + try: + brm.delete() + except ldap.NO_SUCH_OBJECT: + pass + brm.create(properties={ + 'cn': brm.common_name, + 'userPassword': replication_manager_pwd + }) + replication_manager_dn = brm.dn + + replica = Replicas(inst).get(DEFAULT_SUFFIX) + replica.set('nsDS5ReplicaBindDN', brm.dn) + replica.remove_all('nsDS5ReplicaBindDNgroup') + agmt = replica.get_agreements().list()[0] + agmt.replace_many( + ('nsDS5ReplicaBindMethod', 'SASL/DIGEST-MD5'), + ('nsDS5ReplicaTransportInfo', 'LDAP'), + ('nsDS5ReplicaPort', str(to.port)), + ('nsDS5ReplicaBindDN', replication_manager_dn), + ('nsDS5ReplicaCredentials', replication_manager_pwd), + ) + + +def gen_valgrind_wrapper(dir): + name=f"{dir}/VALGRIND" + with open(name, 'w') as f: + f.write('#!/bin/sh\n') + f.write('export SASL_PATH=foo\n') + f.write(f'valgrind -q --tool=memcheck --leak-check=yes --leak-resolution=high --num-callers=50 --log-file=/var/tmp/slapd.vg.$$ {dir}/ns-slapd.original "$@"\n') + os.chmod(name, 0o755) + return name + [email protected] +def use_valgrind(topo_m2, request): + """Adds entries to the supplier1""" + + log.info("Enable valgrind") + m1 = topo_m2.ms['supplier1'] + m2 = topo_m2.ms['supplier2'] + if m1.has_asan(): + pytest.skip('Tescase using valgring cannot run on asan enabled build') + return + set_sasl_md5_client_auth(m1, m2) + set_sasl_md5_client_auth(m2, m1) + m1.stop() + m2.stop() + m1.systemd_override = False + m2.systemd_override = False + valgrind_enable(m1.ds_paths.sbin_dir, gen_valgrind_wrapper(m1.ds_paths.sbin_dir)) + + def fin(): + log.info("Disable valgrind") + valgrind_disable(m1.ds_paths.sbin_dir) + + request.addfinalizer(fin) + + +def test_repl_sasl_md5_auth(topo_m2): + """Test replication with SASL digest-md5 authentication + + :id: 922d16f8-662a-4915-a39e-0aecd7c8e6e2 + :setup: Two supplier replication + :steps: + 1. Set sasl digest/md4 on both suppliers + 2. Restart the instance + 3. Check that replication works + :expectedresults: + 1. Success + 2. Success + 3. Replication works + """ + + m1 = topo_m2.ms['supplier1'] + m2 = topo_m2.ms['supplier2'] + + set_sasl_md5_client_auth(m1, m2) + set_sasl_md5_client_auth(m2, m1) + + m1.restart() + m2.restart() + + repl = ReplicationManager(DEFAULT_SUFFIX) + repl.test_replication_topology(topo_m2) + + [email protected](not os.path.exists('/usr/bin/valgrind'), reason="valgrind is not installed.") +def test_repl_sasl_leak(topo_m2, use_valgrind): + """Test replication with SASL digest-md5 authentication + + :id: 180e088e-841c-11ec-af4f-482ae39447e5 + :setup: Two supplier replication, valgrind + :steps: + 1. Set sasl digest/md4 on both suppliers + 2. Break sasl by setting invalid PATH + 3. Restart the instances + 4. Perform a change + 5. Poke replication 100 times + 6. Stop server + 7. Check presence of "SASL(-4): no mechanism available: No worthy mechs found" message in error log + 8 Check that there is no leak about slapi_ldap_get_lderrno + :expectedresults: + 1. Success + 2. Success + 2. Success + 4. Success + 5. Success + 6. Success + 7. Success + 8. Success + """ + + m1 = topo_m2.ms['supplier1'] + m2 = topo_m2.ms['supplier2'] + + os.environ["SASL_PATH"] = 'foo' + + m1.start() + m2.start() + + resfile=valgrind_get_results_file(m1) + + # Perform a change + from_groups = Groups(m1, basedn=DEFAULT_SUFFIX, rdn=None) + from_group = from_groups.get('replication_managers') + change = str(uuid.uuid4()) + from_group.replace('description', change) + + # Poke replication to trigger thev leak + replica = Replicas(m1).get(DEFAULT_SUFFIX) + agmt = Agreements(m1, replica.dn).list()[0] + for i in range(0, 100): + agmt.pause() + agmt.resume() + + m1.stop() + assert m1.searchErrorsLog("worthy") + assert not valgrind_check_file(resfile, 'slapi_ldap_get_lderrno'); + diff --git a/ldap/servers/plugins/chainingdb/cb_search.c b/ldap/servers/plugins/chainingdb/cb_search.c index 1fb2aaae8..aaac0ff3e 100644 --- a/ldap/servers/plugins/chainingdb/cb_search.c +++ b/ldap/servers/plugins/chainingdb/cb_search.c @@ -348,10 +348,9 @@ chainingdb_build_candidate_list(Slapi_PBlock *pb) warned_rc = 1; } cb_send_ldap_result(pb, rc, NULL, ENDUSERMSG, 0, NULL); - /* BEWARE: matched_msg and error_msg points */ + /* BEWARE: matched_msg points */ /* to ld fields. */ matched_msg = NULL; - error_msg = NULL; rc = -1; } @@ -694,10 +693,9 @@ chainingdb_next_search_entry(Slapi_PBlock *pb) } cb_send_ldap_result(pb, rc, matched_msg, ENDUSERMSG, 0, NULL); - /* BEWARE: Don't free matched_msg && error_msg */ + /* BEWARE: Don't free matched_msg */ /* Points to the ld fields */ matched_msg = NULL; - error_msg = NULL; retcode = -1; } else { /* Add control response sent by the farm server */ diff --git a/ldap/servers/plugins/passthru/ptbind.c b/ldap/servers/plugins/passthru/ptbind.c index 705ab2c3a..3e79b47f6 100644 --- a/ldap/servers/plugins/passthru/ptbind.c +++ b/ldap/servers/plugins/passthru/ptbind.c @@ -33,6 +33,8 @@ passthru_simple_bind_once_s(PassThruServer *srvr, const char *dn, struct berval * are only interested in recovering silently when the remote server is up * but decided to close our connection, we retry without pausing between * attempts. + * + * Note that errmsgp must be freed by the caller. */ int passthru_simple_bind_s(Slapi_PBlock *pb, PassThruServer *srvr, int tries, const char *dn, struct berval *creds, LDAPControl **reqctrls, int *lderrnop, char **matcheddnp, char **errmsgp, struct berval ***refurlsp, LDAPControl ***resctrlsp) diff --git a/ldap/servers/plugins/replication/repl5_connection.c b/ldap/servers/plugins/replication/repl5_connection.c index 2dd74f9e7..b6bc21c46 100644 --- a/ldap/servers/plugins/replication/repl5_connection.c +++ b/ldap/servers/plugins/replication/repl5_connection.c @@ -244,6 +244,7 @@ conn_delete_internal(Repl_Connection *conn) PR_ASSERT(NULL != conn); close_connection_internal(conn); /* slapi_ch_free accepts NULL pointer */ + slapi_ch_free_string(&conn->last_ldap_errmsg); slapi_ch_free((void **)&conn->hostname); slapi_ch_free((void **)&conn->binddn); slapi_ch_free((void **)&conn->plain); @@ -450,6 +451,7 @@ conn_read_result_ex(Repl_Connection *conn, char **retoidp, struct berval **retda char *s = NULL; rc = slapi_ldap_get_lderrno(conn->ld, NULL, &s); + slapi_ch_free_string(&conn->last_ldap_errmsg); conn->last_ldap_errmsg = s; conn->last_ldap_error = rc; /* some errors will require a disconnect and retry the connection @@ -1937,6 +1939,7 @@ bind_and_check_pwp(Repl_Connection *conn, char *binddn, char *password) agmt_get_long_name(conn->agmt), mech ? mech : "SIMPLE", rc, ldap_err2string(rc), errmsg ? errmsg : ""); + slapi_ch_free_string(&errmsg); } else { char *errmsg = NULL; /* errmsg is a pointer directly into the ld structure - do not free */ @@ -1946,6 +1949,7 @@ bind_and_check_pwp(Repl_Connection *conn, char *binddn, char *password) agmt_get_long_name(conn->agmt), mech ? mech : "SIMPLE", rc, ldap_err2string(rc), errmsg ? errmsg : ""); + slapi_ch_free_string(&errmsg); } return (CONN_OPERATION_FAILED); diff --git a/ldap/servers/plugins/replication/windows_connection.c b/ldap/servers/plugins/replication/windows_connection.c index 5eca5fad1..d3f6a4e93 100644 --- a/ldap/servers/plugins/replication/windows_connection.c +++ b/ldap/servers/plugins/replication/windows_connection.c @@ -331,6 +331,7 @@ windows_perform_operation(Repl_Connection *conn, int optype, const char *dn, LDA "windows_perform_operation - %s: Received error %d: %s for %s operation\n", agmt_get_long_name(conn->agmt), rc, s ? s : "NULL", op_string); + slapi_ch_free_string(&s); conn->last_ldap_error = rc; /* some errors will require a disconnect and retry the connection later */ @@ -1709,6 +1710,7 @@ bind_and_check_pwp(Repl_Connection *conn, char *binddn, char *password) agmt_get_long_name(conn->agmt), mech ? mech : "SIMPLE", rc, ldap_err2string(rc), errmsg); + slapi_ch_free_string(&errmsg); } else { char *errmsg = NULL; /* errmsg is a pointer directly into the ld structure - do not free */ @@ -1718,6 +1720,7 @@ bind_and_check_pwp(Repl_Connection *conn, char *binddn, char *password) agmt_get_long_name(conn->agmt), mech ? mech : "SIMPLE", rc, ldap_err2string(rc), errmsg); + slapi_ch_free_string(&errmsg); } slapi_log_err(SLAPI_LOG_TRACE, windows_repl_plugin_name, "<= bind_and_check_pwp - CONN_OPERATION_FAILED\n"); diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index 1e0aa8b14..6e6d61af1 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -367,6 +367,8 @@ slapi_ldap_url_parse(const char *url, LDAPURLDesc **ludpp, int require_dn, int * #include <sasl/sasl.h> + +/* Warning: caller must free s (if not NULL) */ int slapi_ldap_get_lderrno(LDAP *ld, char **m, char **s) { @@ -381,6 +383,9 @@ slapi_ldap_get_lderrno(LDAP *ld, char **m, char **s) ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, s); #else ldap_get_option(ld, LDAP_OPT_ERROR_STRING, s); + if (*s) { + *s = slapi_ch_strdup(*s); + } #endif } return rc; @@ -1494,6 +1499,7 @@ slapd_ldap_sasl_interactive_bind( mech ? mech : "SIMPLE", rc, ldap_err2string(rc), errmsg, errno, slapd_system_strerror(errno)); + slapi_ch_free_string(&errmsg); if (can_retry_bind(ld, mech, bindid, creds, rc, errmsg)) { ; /* pass through to retry one time */ } else { diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index 48d3879a3..1c314322b 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -67,6 +67,34 @@ def _gen_filter(attrtypes, values, extra=None): return filt +# Define wrappers around the ldap operation to have a clear diagnostic +def _ldap_op_s(inst, f, fname, *args, **kwargs): + # f.__name__ says 'inner' so the wanted name is provided as argument + try: + return f(*args, **kwargs) + except ldap.LDAPError as e: + new_desc = f"{fname}({args},{kwargs}) on instance {inst.serverid}"; + if len(e.args) >= 1: + e.args[0]['ldap_request'] = new_desc + logging.getLogger().error(f"args={e.args}") + raise + +def _add_ext_s(inst, *args, **kwargs): + return _ldap_op_s(inst, inst.add_ext_s, 'add_ext_s', *args, **kwargs) + +def _modify_ext_s(inst, *args, **kwargs): + return _ldap_op_s(inst, inst.modify_ext_s, 'modify_ext_s', *args, **kwargs) + +def _delete_ext_s(inst, *args, **kwargs): + return _ldap_op_s(inst, inst.delete_ext_s, 'delete_ext_s', *args, **kwargs) + +def _search_ext_s(inst, *args, **kwargs): + return _ldap_op_s(inst, inst.search_ext_s, 'search_ext_s', *args, **kwargs) + +def _search_s(inst, *args, **kwargs): + return _ldap_op_s(inst, inst.search_s, 'search_s', *args, **kwargs) + + class DSLogging(object): """The benefit of this is automatic name detection, and correct application of level and verbosity to the object. @@ -129,7 +157,7 @@ class DSLdapObject(DSLogging, DSLint): :returns: Entry object """ - return self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], + return _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] @@ -140,7 +168,7 @@ class DSLdapObject(DSLogging, DSLint): """ try: - self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, + _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') except ldap.NO_SUCH_OBJECT: @@ -156,7 +184,7 @@ class DSLdapObject(DSLogging, DSLint): search_scope = ldap.SCOPE_ONE elif scope == 'subtree': search_scope = ldap.SCOPE_SUBTREE - return self._instance.search_ext_s(self._dn, search_scope, filter, + return _search_ext_s(self._instance,self._dn, search_scope, filter, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') @@ -166,7 +194,7 @@ class DSLdapObject(DSLogging, DSLint): :returns: LDIF formatted string """ - e = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=attrlist, + e = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=attrlist, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return e.__repr__() @@ -258,7 +286,7 @@ class DSLdapObject(DSLogging, DSLint): raise ValueError("Invalid state. Cannot get presence on instance that is not ONLINE") self._log.debug("%s present(%r) %s" % (self._dn, attr, value)) - self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], + _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[attr, ], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] values = self.get_attr_vals_bytes(attr) @@ -313,7 +341,7 @@ class DSLdapObject(DSLogging, DSLint): else: value = [ensure_bytes(arg[1])] mods.append((ldap.MOD_REPLACE, ensure_str(arg[0]), value)) - return self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, + return _modify_ext_s(self._instance,self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') # This needs to work on key + val, and key @@ -457,7 +485,7 @@ class DSLdapObject(DSLogging, DSLint): elif value is not None: value = [ensure_bytes(value)] - return self._instance.modify_ext_s(self._dn, [(action, key, value)], + return _modify_ext_s(self._instance,self._dn, [(action, key, value)], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') @@ -497,7 +525,7 @@ class DSLdapObject(DSLogging, DSLint): else: # Error too many items raise ValueError('Too many arguments in the mod op') - return self._instance.modify_ext_s(self._dn, mod_list, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + return _modify_ext_s(self._instance,self._dn, mod_list, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') def _unsafe_compare_attribute(self, other): """Compare two attributes from two objects. This is currently marked unsafe as it's @@ -593,7 +621,7 @@ class DSLdapObject(DSLogging, DSLint): raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") else: # retrieving real(*) and operational attributes(+) - attrs_entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + attrs_entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*", "+"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] # getting dict from 'entry' object @@ -613,7 +641,7 @@ class DSLdapObject(DSLogging, DSLint): raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") else: # retrieving real(*) and operational attributes(+) - attrs_entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + attrs_entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=["*", "+"], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] # getting dict from 'entry' object @@ -627,7 +655,7 @@ class DSLdapObject(DSLogging, DSLint): if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") else: - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return entry.getValuesSet(keys) @@ -636,7 +664,7 @@ class DSLdapObject(DSLogging, DSLint): self._log.debug("%s get_attrs_vals_utf8(%r)" % (self._dn, keys)) if self._instance.state != DIRSRV_STATE_ONLINE: raise ValueError("Invalid state. Cannot get properties on instance that is not ONLINE") - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, + entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=keys, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] vset = entry.getValuesSet(keys) @@ -655,7 +683,7 @@ class DSLdapObject(DSLogging, DSLint): else: # It would be good to prevent the entry code intercepting this .... # We have to do this in this method, because else we ignore the scope base. - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] vals = entry.getValues(key) @@ -675,7 +703,7 @@ class DSLdapObject(DSLogging, DSLint): # In the future, I plan to add a mode where if local == true, we # can use get on dse.ldif to get values offline. else: - entry = self._instance.search_ext_s(self._dn, ldap.SCOPE_BASE, self._object_filter, + entry = _search_ext_s(self._instance,self._dn, ldap.SCOPE_BASE, self._object_filter, attrlist=[key], serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure')[0] return entry.getValue(key) @@ -831,11 +859,11 @@ class DSLdapObject(DSLogging, DSLint): # Is there a way to mark this as offline and kill it if recursive: filterstr = "(|(objectclass=*)(objectclass=ldapsubentry))" - ents = self._instance.search_s(self._dn, ldap.SCOPE_SUBTREE, filterstr, escapehatch='i am sure') + ents = _search_s(self._instance, self._dn, ldap.SCOPE_SUBTREE, filterstr, escapehatch='i am sure') for ent in sorted(ents, key=lambda e: len(e.dn), reverse=True): - self._instance.delete_ext_s(ent.dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + _delete_ext_s(self._instance, ent.dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') else: - self._instance.delete_ext_s(self._dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + _delete_ext_s(self._instance, self._dn, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') def _validate(self, rdn, properties, basedn): """Used to validate a create request. @@ -933,7 +961,7 @@ class DSLdapObject(DSLogging, DSLint): # If we are running in stateful ensure mode, we need to check if the object exists, and # we can see the state that it is in. try: - self._instance.search_ext_s(dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + _search_ext_s(self._instance,dn, ldap.SCOPE_BASE, self._object_filter, attrsonly=1, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') exists = True except ldap.NO_SUCH_OBJECT: pass @@ -946,7 +974,7 @@ class DSLdapObject(DSLogging, DSLint): mods = [] for k, v in list(valid_props.items()): mods.append((ldap.MOD_REPLACE, k, v)) - self._instance.modify_ext_s(self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + _modify_ext_s(self._instance,self._dn, mods, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') elif not exists: # This case is reached in two cases. One is we are in ensure mode, and we KNOW the entry # doesn't exist. @@ -957,7 +985,7 @@ class DSLdapObject(DSLogging, DSLint): e.update({'objectclass': ensure_list_bytes(self._create_objectclasses)}) e.update(valid_props) # We rely on exceptions here to indicate failure to the parent. - self._instance.add_ext_s(e, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') + _add_ext_s(self._instance, e, serverctrls=self._server_controls, clientctrls=self._client_controls, escapehatch='i am sure') self._log.debug('Created entry %s : %s' % (dn, display_log_data(e.data))) # If it worked, we need to fix our instance dn for the object's self reference. Because # we may not have a self reference yet (just created), it may have changed (someone @@ -1104,7 +1132,7 @@ class DSLdapObjects(DSLogging, DSLints): else: # If not paged try: - results = self._instance.search_ext_s( + results = _search_ext_s(self._instance, base=self._basedn, scope=self._scope, filterstr=filterstr, @@ -1172,7 +1200,7 @@ class DSLdapObjects(DSLogging, DSLints): filterstr = self._get_objectclass_filter() self._log.debug('_gen_dn filter = %s' % filterstr) self._log.debug('_gen_dn dn = %s' % dn) - return self._instance.search_ext_s( + return _search_ext_s(self._instance, base=dn, scope=ldap.SCOPE_BASE, filterstr=filterstr, @@ -1187,7 +1215,7 @@ class DSLdapObjects(DSLogging, DSLints): # This will yield and & filter for objectClass with as many terms as needed. filterstr = self._get_selector_filter(selector) self._log.debug('_gen_selector filter = %s' % filterstr) - return self._instance.search_ext_s( + return _search_ext_s(self._instance, base=self._basedn, scope=self._scope, filterstr=filterstr, @@ -1261,7 +1289,7 @@ class DSLdapObjects(DSLogging, DSLints): self._list_attrlist = attrlist self._log.debug(f'list filter = {search_filter} with scope {scope} and attribute list {attrlist}') try: - results = self._instance.search_ext_s( + results = _search_ext_s(self._instance, base=self._basedn, scope=scope, filterstr=search_filter, diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index f641e44dd..09c50cd19 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -51,7 +51,7 @@ from ldapurl import LDAPUrl from contextlib import closing import lib389 -from lib389.paths import Paths +from lib389.paths import ( Paths, DEFAULTS_PATH ) from lib389.dseldif import DSEldif from lib389._constants import ( DEFAULT_USER, VALGRIND_WRAPPER, DN_CONFIG, CFGSUFFIX, LOCALHOST, @@ -494,8 +494,10 @@ def valgrind_enable(sbin_dir, wrapper=None): :raise EnvironmentError: If script is not run as 'root' ''' - if os.geteuid() != 0: - log.error('This script must be run as root to use valgrind') + if not os.access(sbin_dir, os.W_OK): + # Note: valgrind has no limitation but ns-slapd must be replaced + # This check allows non root user to use custom install prefix + log.error('This script must be run as root to use valgrind (Should at least be able to write in {sbin_dir})') raise EnvironmentError if not wrapper: @@ -541,7 +543,20 @@ def valgrind_enable(sbin_dir, wrapper=None): e.strerror) # Disable selinux - os.system('setenforce 0') + if os.geteuid() == 0: + os.system('setenforce 0') + + # Disable systemd by turning off with_system in .inf file + old_path = Paths()._get_defaults_loc(DEFAULTS_PATH) + new_path = f'{old_path}.orig' + os.rename(old_path, new_path) + with open(new_path, 'rt') as fin: + with open(old_path, 'wt') as fout: + for line in fin: + if line.startswith('with_systemd'): + fout.write('with_systemd = 0\n') + else: + fout.write(line) log.info('Valgrind is now enabled.') @@ -558,8 +573,10 @@ def valgrind_disable(sbin_dir): :raise EnvironmentError: If script is not run as 'root' ''' - if os.geteuid() != 0: - log.error('This script must be run as root to use valgrind') + if not os.access(sbin_dir, os.W_OK): + # Note: valgrind has no limitation but ns-slapd must be replaced + # This check allows non root user to use custom install prefix + log.error('This script must be run as root to use valgrind (Should at least be able to write in {sbin_dir})') raise EnvironmentError nsslapd_orig = '%s/ns-slapd' % sbin_dir @@ -583,7 +600,14 @@ def valgrind_disable(sbin_dir): e.strerror) # Enable selinux - os.system('setenforce 1') + if os.geteuid() == 0: + os.system('setenforce 1') + + # Restore .inf file (for systemd) + new_path = Paths()._get_defaults_loc(DEFAULTS_PATH) + old_path = f'{new_path}.orig' + if os.path.exists(old_path): + os.replace(old_path, new_path) log.info('Valgrind is now disabled.') @@ -609,7 +633,7 @@ def valgrind_get_results_file(dirsrv_inst): # Run the command and grab the output p = os.popen(cmd) - results_file = p.readline() + results_file = p.readline().strip() p.close() return results_file
0
ed2875b4c8895c85f4f21068fb6a0c146536ae04
389ds/389-ds-base
Ticket 49042 - Increase cache defaults slightly Bug Description: We have very small defaults for most sites right now. If we increase these, we will see a benefit to performance and reduction in cache eviction. It will help freeipa with it's out of box performance issue before we move to the full automatic tuning. Fix Description: Change the defaults: dbcachesize 10MB -> 32MB entrycachesize 10MB -> 32MB dncachesize 10MB -> 16MB https://fedorahosted.org/389/ticket/49042 Author: wibrown Review by: ???
commit ed2875b4c8895c85f4f21068fb6a0c146536ae04 Author: William Brown <[email protected]> Date: Fri Nov 18 10:11:50 2016 +1000 Ticket 49042 - Increase cache defaults slightly Bug Description: We have very small defaults for most sites right now. If we increase these, we will see a benefit to performance and reduction in cache eviction. It will help freeipa with it's out of box performance issue before we move to the full automatic tuning. Fix Description: Change the defaults: dbcachesize 10MB -> 32MB entrycachesize 10MB -> 32MB dncachesize 10MB -> 16MB https://fedorahosted.org/389/ticket/49042 Author: wibrown Review by: ??? diff --git a/ldap/servers/slapd/back-ldbm/back-ldbm.h b/ldap/servers/slapd/back-ldbm/back-ldbm.h index 8b63e2c7c..ecef9567e 100644 --- a/ldap/servers/slapd/back-ldbm/back-ldbm.h +++ b/ldap/servers/slapd/back-ldbm/back-ldbm.h @@ -160,11 +160,14 @@ typedef unsigned short u_int16_t; #define LDBM_VERSION_31 "Netscape-ldbm/3.1" #define LDBM_FILENAME_SUFFIX LDBM_SUFFIX #define DBVERSION_FILENAME "DBVERSION" -#define DEFAULT_CACHE_SIZE (size_t)10485760 +#define DEFAULT_CACHE_SIZE (size_t)33554432 +#define DEFAULT_CACHE_SIZE_STR "33554432" #define DEFAULT_CACHE_ENTRIES -1 /* no limit */ -#define DEFAULT_DNCACHE_SIZE (size_t)10485760 +#define DEFAULT_DNCACHE_SIZE (size_t)16777216 +#define DEFAULT_DNCACHE_SIZE_STR "16777216" #define DEFAULT_DNCACHE_MAXCOUNT -1 /* no limit */ -#define DEFAULT_DBCACHE_SIZE 1000000 +#define DEFAULT_DBCACHE_SIZE 33554432 +#define DEFAULT_DBCACHE_SIZE_STR "33554432" #define DEFAULT_MODE 0600 #define DEFAULT_ALLIDSTHRESHOLD 4000 #define DEFAULT_IDL_TUNE 1 diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index 56792c390..04d31b12b 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -2348,7 +2348,7 @@ dblayer_get_aux_id2entry_ext(backend *be, DB **ppDB, DB_ENV **ppEnv, } envflags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE; - cachesize = 10485760; /* 10M */ + cachesize = DEFAULT_DBCACHE_SIZE; if (!*ppEnv) { mypEnv->dblayer_DB_ENV->set_cachesize(mypEnv->dblayer_DB_ENV, diff --git a/ldap/servers/slapd/back-ldbm/ldbm_config.c b/ldap/servers/slapd/back-ldbm/ldbm_config.c index 0aac833af..4b612db44 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_config.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_config.c @@ -1501,7 +1501,7 @@ static config_info ldbm_config[] = { {CONFIG_MODE, CONFIG_TYPE_INT_OCTAL, "0600", &ldbm_config_mode_get, &ldbm_config_mode_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_IDLISTSCANLIMIT, CONFIG_TYPE_INT, "4000", &ldbm_config_allidsthreshold_get, &ldbm_config_allidsthreshold_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DIRECTORY, CONFIG_TYPE_STRING, "", &ldbm_config_directory_get, &ldbm_config_directory_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE|CONFIG_FLAG_SKIP_DEFAULT_SETTING}, - {CONFIG_DBCACHESIZE, CONFIG_TYPE_SIZE_T, "10000000", &ldbm_config_dbcachesize_get, &ldbm_config_dbcachesize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, + {CONFIG_DBCACHESIZE, CONFIG_TYPE_SIZE_T, DEFAULT_DBCACHE_SIZE_STR, &ldbm_config_dbcachesize_get, &ldbm_config_dbcachesize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_DBNCACHE, CONFIG_TYPE_INT, "0", &ldbm_config_dbncache_get, &ldbm_config_dbncache_set, CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_MAXPASSBEFOREMERGE, CONFIG_TYPE_INT, "100", &ldbm_config_maxpassbeforemerge_get, &ldbm_config_maxpassbeforemerge_set, 0}, diff --git a/ldap/servers/slapd/back-ldbm/ldbm_instance_config.c b/ldap/servers/slapd/back-ldbm/ldbm_instance_config.c index 2d23ea5c7..e03954d62 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_instance_config.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_instance_config.c @@ -297,11 +297,11 @@ ldbm_instance_config_require_index_set(void *arg, void *value, char *errorbuf, i *----------------------------------------------------------------------*/ static config_info ldbm_instance_config[] = { {CONFIG_INSTANCE_CACHESIZE, CONFIG_TYPE_LONG, "-1", &ldbm_instance_config_cachesize_get, &ldbm_instance_config_cachesize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, - {CONFIG_INSTANCE_CACHEMEMSIZE, CONFIG_TYPE_SIZE_T, "10485760", &ldbm_instance_config_cachememsize_get, &ldbm_instance_config_cachememsize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, + {CONFIG_INSTANCE_CACHEMEMSIZE, CONFIG_TYPE_SIZE_T, DEFAULT_CACHE_SIZE_STR, &ldbm_instance_config_cachememsize_get, &ldbm_instance_config_cachememsize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_INSTANCE_READONLY, CONFIG_TYPE_ONOFF, "off", &ldbm_instance_config_readonly_get, &ldbm_instance_config_readonly_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_INSTANCE_REQUIRE_INDEX, CONFIG_TYPE_ONOFF, "off", &ldbm_instance_config_require_index_get, &ldbm_instance_config_require_index_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {CONFIG_INSTANCE_DIR, CONFIG_TYPE_STRING, NULL, &ldbm_instance_config_instance_dir_get, &ldbm_instance_config_instance_dir_set, CONFIG_FLAG_ALWAYS_SHOW}, - {CONFIG_INSTANCE_DNCACHEMEMSIZE, CONFIG_TYPE_SIZE_T, "10485760", &ldbm_instance_config_dncachememsize_get, &ldbm_instance_config_dncachememsize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, + {CONFIG_INSTANCE_DNCACHEMEMSIZE, CONFIG_TYPE_SIZE_T, DEFAULT_DNCACHE_SIZE_STR, &ldbm_instance_config_dncachememsize_get, &ldbm_instance_config_dncachememsize_set, CONFIG_FLAG_ALWAYS_SHOW|CONFIG_FLAG_ALLOW_RUNNING_CHANGE}, {NULL, 0, NULL, NULL, NULL, 0} };
0
5c3eb36aaa05e9cd4eaa923e337d3b55cf584a39
389ds/389-ds-base
504383 PCRE breaks SASL Mapping Fix Description: unescape parenthesis in the regular expression. E.g., ^u:\(.*\) ==> ^u:(.*) This unescape is necessary for the new regex code using PCRE to keep the backward compatibility.
commit 5c3eb36aaa05e9cd4eaa923e337d3b55cf584a39 Author: Noriko Hosoi <[email protected]> Date: Tue Jun 23 13:51:14 2009 -0700 504383 PCRE breaks SASL Mapping Fix Description: unescape parenthesis in the regular expression. E.g., ^u:\(.*\) ==> ^u:(.*) This unescape is necessary for the new regex code using PCRE to keep the backward compatibility. diff --git a/ldap/servers/slapd/sasl_map.c b/ldap/servers/slapd/sasl_map.c index 10a0cf4a3..637ea5dca 100644 --- a/ldap/servers/slapd/sasl_map.c +++ b/ldap/servers/slapd/sasl_map.c @@ -274,6 +274,29 @@ freeConfigEntry( Slapi_Entry ** e ) { } } +/* + * unescape parenthesis in the regular expression. + * E.g., ^u:\(.*\) ==> ^u:(.*) + * This unescape is necessary for the new regex code using PCRE + * to keep the backward compatibility. + */ +char * +_sasl_unescape_parenthesis(char *input) +{ + char *s = NULL; + char *d = NULL; + + for (s = input, d = input; s && *s; s++) { + if (*s == '\\' && *(s+1) && (*(s+1) == '(' || *(s+1) == ')')) { + *d++ = *(++s); + } else { + *d++ = *s; + } + } + *d = '\0'; + return input; +} + static int sasl_map_config_parse_entry(Slapi_Entry *entry, sasl_map_data **new_dp) { @@ -284,7 +307,7 @@ sasl_map_config_parse_entry(Slapi_Entry *entry, sasl_map_data **new_dp) char *map_name = NULL; *new_dp = NULL; - regex = slapi_entry_attr_get_charptr( entry, "nsSaslMapRegexString" ); + regex = _sasl_unescape_parenthesis(slapi_entry_attr_get_charptr( entry, "nsSaslMapRegexString" )); basedntemplate = slapi_entry_attr_get_charptr( entry, "nsSaslMapBaseDNTemplate" ); filtertemplate = slapi_entry_attr_get_charptr( entry, "nsSaslMapFilterTemplate" ); map_name = slapi_entry_attr_get_charptr( entry, "cn" );
0
2aae0e55cf261c428292d391fd885d31e3de041a
389ds/389-ds-base
Bug 614511 - fix coverify Defect Type: Null pointer dereferences issues 11846 - 11891 https://bugzilla.redhat.com/show_bug.cgi?id=614511 Resolves: bug 614511 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11846 - 11891 description: Catch possible NULL pointer in memberof_get_groups_callback().
commit 2aae0e55cf261c428292d391fd885d31e3de041a Author: Endi S. Dewata <[email protected]> Date: Mon Jul 12 23:08:43 2010 -0500 Bug 614511 - fix coverify Defect Type: Null pointer dereferences issues 11846 - 11891 https://bugzilla.redhat.com/show_bug.cgi?id=614511 Resolves: bug 614511 Bug description: Fix coverify Defect Type: Null pointer dereferences issues 11846 - 11891 description: Catch possible NULL pointer in memberof_get_groups_callback(). diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index 85bcdcbb1..919a95e33 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -1439,7 +1439,16 @@ int memberof_get_groups_callback(Slapi_Entry *e, void *callback_data) char *group_dn = slapi_entry_get_dn(e); Slapi_Value *group_dn_val = 0; Slapi_ValueSet *groupvals = *((memberof_get_groups_data*)callback_data)->groupvals; + int rc = 0; + if (!groupvals) + { + slapi_log_error( SLAPI_LOG_PLUGIN, MEMBEROF_PLUGIN_SUBSYSTEM, + "memberof_get_groups_callback: NULL groupvals\n"); + rc = -1; + goto bail; + + } /* get the DN of the group */ group_dn_val = slapi_value_new_string(group_dn); @@ -1459,8 +1468,7 @@ int memberof_get_groups_callback(Slapi_Entry *e, void *callback_data) } /* have we been here before? */ - if (groupvals && - slapi_valueset_find(((memberof_get_groups_data*)callback_data)->config->group_slapiattr, + if (slapi_valueset_find(((memberof_get_groups_data*)callback_data)->config->group_slapiattr, groupvals, group_dn_val)) { /* we either hit a recursive grouping, or an entry is @@ -1482,8 +1490,8 @@ int memberof_get_groups_callback(Slapi_Entry *e, void *callback_data) memberof_get_groups_r(((memberof_get_groups_data*)callback_data)->config, group_dn, callback_data); - bail: - return 0; +bail: + return rc; } /* memberof_is_direct_member()
0
473d61634aff177b23520bf6c1fd85de6cee3718
389ds/389-ds-base
Ticket 50857 - Memory leak in ACI using IP subject Bug Description: When a ACI is evaluated (LASIpEval) a context (cookie) is allocated. At the end of the connection, the context is freed via a callback (LASIpFlush). The context contains two LASIpTree_t tree (ipv4 and ipv6) In free callback, only ipv4 tree is freed Fix Description: Free ipv6 tree in LASIpTree https://pagure.io/389-ds-base/issue/50857 Reviewed by: Mark Reynolds Platforms tested: F31 Flag Day: no Doc impact: no
commit 473d61634aff177b23520bf6c1fd85de6cee3718 Author: Thierry Bordaz <[email protected]> Date: Mon Jan 27 13:49:37 2020 +0100 Ticket 50857 - Memory leak in ACI using IP subject Bug Description: When a ACI is evaluated (LASIpEval) a context (cookie) is allocated. At the end of the connection, the context is freed via a callback (LASIpFlush). The context contains two LASIpTree_t tree (ipv4 and ipv6) In free callback, only ipv4 tree is freed Fix Description: Free ipv6 tree in LASIpTree https://pagure.io/389-ds-base/issue/50857 Reviewed by: Mark Reynolds Platforms tested: F31 Flag Day: no Doc impact: no diff --git a/lib/libaccess/lasip.cpp b/lib/libaccess/lasip.cpp index 30c546df7..cdb88eec5 100644 --- a/lib/libaccess/lasip.cpp +++ b/lib/libaccess/lasip.cpp @@ -436,6 +436,7 @@ LASIpFlush(void **las_cookie) return; LASIpTreeDealloc(((LASIpContext_t *)*las_cookie)->treetop); + LASIpTreeDealloc(((LASIpContext_t *)*las_cookie)->treetop_ipv6); PERM_FREE(*las_cookie); *las_cookie = NULL; return;
0
2a9df10303c4902a816a64b805448f31380a2728
389ds/389-ds-base
Issue 4513 - fix ACI CI tests involving ip/hostname rules Description: Fix tests that use ACIs with ip/hostname rules. Harden the dscreate and dsctl acceptance tests, and fix some flakiness in the sync repl test, and filter schema validation. Also updated the doxy file and fixed some compiler warnings relates: https://github.com/389ds/389-ds-base/issues/4513 Reviewed by: spichugi & tbordaz(Thanks!!)
commit 2a9df10303c4902a816a64b805448f31380a2728 Author: Mark Reynolds <[email protected]> Date: Wed Sep 22 10:50:51 2021 -0400 Issue 4513 - fix ACI CI tests involving ip/hostname rules Description: Fix tests that use ACIs with ip/hostname rules. Harden the dscreate and dsctl acceptance tests, and fix some flakiness in the sync repl test, and filter schema validation. Also updated the doxy file and fixed some compiler warnings relates: https://github.com/389ds/389-ds-base/issues/4513 Reviewed by: spichugi & tbordaz(Thanks!!) diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 8755433d0..d96534b22 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -69,14 +69,16 @@ jobs: set -x CID=$(sudo docker run -d -h server.example.com --privileged --rm -v /sys/fs/cgroup:/sys/fs/cgroup:rw,rslave -v ${PWD}:/workspace quay.io/389ds/ci-images:test) sudo docker exec $CID sh -c "dnf install -y -v dist/rpms/*rpm" - sudo docker exec $CID py.test --suppress-no-test-exit-code -m "not flaky" --junit-xml=pytest.xml -v dirsrvtests/tests/suites/${{ matrix.suite }} + sudo docker exec $CID py.test --suppress-no-test-exit-code -m "not flaky" --junit-xml=pytest.xml --html=pytest.html -v dirsrvtests/tests/suites/${{ matrix.suite }} - name: Make the results file readable by all if: always() - run: - sudo chmod -f a+r pytest.xml + run: | + sudo chmod -f -v -R a+r pytest.*ml assets + sudo chmod -f -v a+x assets - name: Sanitize filename + if: always() run: echo "PYTEST_SUITE=$(echo ${{ matrix.suite }} | sed -e 's#\/#-#g')" >> $GITHUB_ENV - name: Upload pytest test results @@ -84,5 +86,8 @@ jobs: uses: actions/upload-artifact@v2 with: name: pytest-${{ env.PYTEST_SUITE }} - path: pytest.xml + path: | + pytest.xml + pytest.html + assets diff --git a/dirsrvtests/conftest.py b/dirsrvtests/conftest.py index 1ac02fae7..01fa30079 100644 --- a/dirsrvtests/conftest.py +++ b/dirsrvtests/conftest.py @@ -108,4 +108,11 @@ def pytest_runtest_makereport(item, call): with open(f) as asan_report: text = asan_report.read() extra.append(pytest_html.extras.text(text, name=os.path.basename(f))) + for f in glob.glob(f'{p.log_dir.split("/slapd",1)[0]}/*/*'): + if 'rotationinfo' not in f: + with open(f) as dirsrv_log: + text = dirsrv_log.read() + log_name = os.path.basename(f) + instance_name = os.path.basename(os.path.dirname(f)).split("slapd-",1)[1] + extra.append(pytest_html.extras.text(text, name=f"{instance_name}-{log_name}")) report.extra = extra diff --git a/dirsrvtests/tests/suites/acl/keywords_part2_test.py b/dirsrvtests/tests/suites/acl/keywords_part2_test.py index 36c2413c2..5b27024d4 100644 --- a/dirsrvtests/tests/suites/acl/keywords_part2_test.py +++ b/dirsrvtests/tests/suites/acl/keywords_part2_test.py @@ -10,23 +10,19 @@ """ This test script will test wrong/correct key value with ACIs. """ - +import ldap import os -import time -from datetime import datetime import pytest import socket - +import time +from datetime import datetime from lib389._constants import DEFAULT_SUFFIX, PW_DM from lib389.idm.domain import Domain from lib389.idm.organizationalunit import OrganizationalUnit from lib389.idm.user import UserAccount -import ldap - pytestmark = pytest.mark.tier1 - KEYWORDS_OU_KEY = "ou=Keywords,{}".format(DEFAULT_SUFFIX) DAYOFWEEK_OU_KEY = "ou=Dayofweek,{}".format(KEYWORDS_OU_KEY) IP_OU_KEY = "ou=IP,{}".format(KEYWORDS_OU_KEY) @@ -66,6 +62,8 @@ def test_access_from_certain_network_only_ip(topo, add_user, aci_of_user): # Wait till Access Log is generated topo.standalone.restart() + old_hostname = socket.gethostname() + socket.sethostname('localhost') hostname = socket.gethostname() IP = socket.gethostbyname(hostname) @@ -75,9 +73,14 @@ def test_access_from_certain_network_only_ip(topo, add_user, aci_of_user): f'allow(all)userdn = "ldap:///{NETSCAPEIP_KEY}" and (ip = "127.0.0.1" or ip = "::1" or ip = "{IP}") ;)') # create a new connection for the test + new_uri = topo.standalone.ldapuri.replace(old_hostname, hostname) + topo.standalone.ldapuri = new_uri conn = UserAccount(topo.standalone, NETSCAPEIP_KEY).bind(PW_DM) + # Perform Operation + topo.standalone.config.set('nsslapd-errorlog-level', '128') org = OrganizationalUnit(conn, IP_OU_KEY) + topo.standalone.host = hostname org.replace("seeAlso", "cn=1") # remove the aci @@ -93,7 +96,7 @@ def test_access_from_certain_network_only_ip(topo, add_user, aci_of_user): org.replace("seeAlso", "cn=1") -def test_connectin_from_an_unauthorized_network(topo, add_user, aci_of_user): +def test_connection_from_an_unauthorized_network(topo, add_user, aci_of_user): """ User cannot access the data when connectin from an unauthorized network as per the ACI. @@ -109,28 +112,35 @@ def test_connectin_from_an_unauthorized_network(topo, add_user, aci_of_user): 2. Operation should succeed 3. Operation should succeed """ + old_hostname = socket.gethostname() + socket.sethostname('localhost') hostname = socket.gethostname() - IP = socket.gethostbyname(hostname) # Add ACI domain = Domain(topo.standalone, DEFAULT_SUFFIX) domain.add("aci", f'(target = "ldap:///{IP_OU_KEY}")' f'(targetattr="*")(version 3.0; aci "IP aci"; ' f'allow(all) userdn = "ldap:///{NETSCAPEIP_KEY}" ' - f'and (ip != "127.0.0.1" and ip != "::1" and ip != "{IP}") ;)') + f'and (ip != "127.0.0.1" and ip != "::1") ;)') # create a new connection for the test + new_uri = topo.standalone.ldapuri.replace(old_hostname, hostname) + topo.standalone.ldapuri = new_uri conn = UserAccount(topo.standalone, NETSCAPEIP_KEY).bind(PW_DM) + # Perform Operation + topo.standalone.config.set('nsslapd-errorlog-level', '128') org = OrganizationalUnit(conn, IP_OU_KEY) with pytest.raises(ldap.INSUFFICIENT_ACCESS): org.replace("seeAlso", "cn=1") + # Remove the ACI domain.ensure_removed('aci', domain.get_attr_vals('aci')[-1]) # Add new ACI domain.add('aci', f'(target = "ldap:///{IP_OU_KEY}")(targetattr="*")' f'(version 3.0; aci "IP aci"; allow(all) ' - f'userdn = "ldap:///{NETSCAPEIP_KEY}" and (ip = "127.0.0.1" or ip = "::1" or ip = "{IP}") ;)') + f'userdn = "ldap:///{NETSCAPEIP_KEY}" and (ip = "127.0.0.1" or ip = "::1") ;)') + time.sleep(1) # now user can access data org.replace("seeAlso", "cn=1") diff --git a/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py b/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py index ec5f09032..796833042 100644 --- a/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py +++ b/dirsrvtests/tests/suites/clu/dsctl_acceptance_test.py @@ -9,7 +9,7 @@ import logging import pytest import os -from lib389._constants import * +import time from lib389.topologies import topology_st as topo log = logging.getLogger(__name__) @@ -36,17 +36,24 @@ def test_custom_path(topo): # Get LDIF dir ldif_dir = topo.standalone.get_ldif_dir() + bak_dir = topo.standalone.get_bak_dir() + log.info("ldif dir: " + ldif_dir + " items: " + str(len(os.listdir(ldif_dir)))) + log.info("bak dir: " + bak_dir + " items: " + str(len(os.listdir(bak_dir)))) # Set backup directory to LDIF directory topo.standalone.config.replace('nsslapd-bakdir', ldif_dir) + time.sleep(.5) # Stop the server and take a backup topo.standalone.stop() - topo.standalone.db2bak(None) + time.sleep(.5) + topo.standalone.db2bak(None) # Bug, bak dir is being pulled from defaults.inf, and not from config # Verify backup was written to LDIF directory - backups = os.listdir(ldif_dir) - assert len(backups) + log.info("AFTER: ldif dir (new bak dir): " + ldif_dir + " items: " + str(len(os.listdir(ldif_dir)))) + log.info("AFTER: bak dir: " + bak_dir + " items: " + str(len(os.listdir(bak_dir)))) + + assert len(os.listdir(ldif_dir)) if __name__ == '__main__': @@ -54,4 +61,3 @@ if __name__ == '__main__': # -s for DEBUG mode CURRENT_FILE = os.path.realpath(__file__) pytest.main(["-s", CURRENT_FILE]) - diff --git a/dirsrvtests/tests/suites/filter/schema_validation_test.py b/dirsrvtests/tests/suites/filter/schema_validation_test.py index 60e9c50fa..da66542d5 100644 --- a/dirsrvtests/tests/suites/filter/schema_validation_test.py +++ b/dirsrvtests/tests/suites/filter/schema_validation_test.py @@ -9,6 +9,7 @@ import pytest import ldap +import time from lib389.topologies import topology_st as topology_st_pre from lib389.dirsrv_log import DirsrvAccessLog from lib389._mapped_object import DSLdapObjects @@ -120,7 +121,7 @@ def test_filter_validation_enabled(topology_st): with pytest.raises(ldap.UNWILLING_TO_PERFORM): # Check a bad complex one does emit an error. - r = raw_objects.filter("(&(a=a)(b=b)(objectClass=*))") + raw_objects.filter("(&(a=a)(b=b)(objectClass=*))") # Does restart work? inst.restart() @@ -148,6 +149,7 @@ def test_filter_validation_warn_safe(topology_st): inst.config.set("nsslapd-verify-filter-schema", "process-safe") # Set the access log to un-buffered so we get it immediately. inst.config.set("nsslapd-accesslog-logbuffering", "off") + time.sleep(.5) # Setup the query object. # Now we don't care if there are any results, we only care about good/bad queries. @@ -162,6 +164,7 @@ def test_filter_validation_warn_safe(topology_st): # Check a good query has no warnings. r = raw_objects.filter("(objectClass=*)") + time.sleep(.5) assert(len(r) > 0) r_s1 = access_log.match(".*notes=F.*") # Should be the same number of log lines IE 0. @@ -169,20 +172,23 @@ def test_filter_validation_warn_safe(topology_st): # Check a bad one DOES emit a warning. r = raw_objects.filter("(a=a)") + time.sleep(.5) assert(len(r) == 0) r_s2 = access_log.match(".*notes=F.*") - # Should be the greate number of log lines IE +1 + # Should be the greater number of log lines IE +1 assert(len(r_init) + 1 == len(r_s2)) # Check a bad complex one does emit a warning. r = raw_objects.filter("(&(a=a)(b=b)(objectClass=*))") + time.sleep(.5) assert(len(r) == 0) r_s3 = access_log.match(".*notes=F.*") - # Should be the greate number of log lines IE +2 + # Should be the greater number of log lines IE +2 assert(len(r_init) + 2 == len(r_s3)) # Check that we can still get things when partial r = raw_objects.filter("(|(a=a)(b=b)(uid=foo))") + time.sleep(.5) assert(len(r) == 1) r_s4 = access_log.match(".*notes=F.*") # Should be the greate number of log lines IE +2 @@ -211,6 +217,7 @@ def test_filter_validation_warn_unsafe(topology_st): inst.config.set("nsslapd-verify-filter-schema", "warn-invalid") # Set the access log to un-buffered so we get it immediately. inst.config.set("nsslapd-accesslog-logbuffering", "off") + time.sleep(.5) # Setup the query object. # Now we don't care if there are any results, we only care about good/bad queries. @@ -225,6 +232,7 @@ def test_filter_validation_warn_unsafe(topology_st): # Check a good query has no warnings. r = raw_objects.filter("(objectClass=*)") + time.sleep(.5) assert(len(r) > 0) r_s1 = access_log.match(".*notes=(U,)?F.*") # Should be the same number of log lines IE 0. @@ -232,23 +240,25 @@ def test_filter_validation_warn_unsafe(topology_st): # Check a bad one DOES emit a warning. r = raw_objects.filter("(a=a)") + time.sleep(.5) assert(len(r) == 1) # NOTE: Unlike warn-process-safely, these become UNINDEXED and show in the logs. r_s2 = access_log.match(".*notes=(U,)?F.*") - # Should be the greate number of log lines IE +1 + # Should be the greater number of log lines IE +1 assert(len(r_init) + 1 == len(r_s2)) # Check a bad complex one does emit a warning. r = raw_objects.filter("(&(a=a)(b=b)(objectClass=*))") + time.sleep(.5) assert(len(r) == 1) r_s3 = access_log.match(".*notes=(U,)?F.*") - # Should be the greate number of log lines IE +2 + # Should be the greater number of log lines IE +2 assert(len(r_init) + 2 == len(r_s3)) # Check that we can still get things when partial r = raw_objects.filter("(|(a=a)(b=b)(uid=foo))") + time.sleep(.5) assert(len(r) == 1) r_s4 = access_log.match(".*notes=(U,)?F.*") - # Should be the greate number of log lines IE +2 + # Should be the greater number of log lines IE +2 assert(len(r_init) + 3 == len(r_s4)) - diff --git a/dirsrvtests/tests/suites/paged_results/paged_results_test.py b/dirsrvtests/tests/suites/paged_results/paged_results_test.py index a89377580..672f7191c 100644 --- a/dirsrvtests/tests/suites/paged_results/paged_results_test.py +++ b/dirsrvtests/tests/suites/paged_results/paged_results_test.py @@ -8,21 +8,17 @@ # import socket from random import sample - import pytest from ldap.controls import SimplePagedResultsControl, GetEffectiveRightsControl from lib389.tasks import * from lib389.utils import * from lib389.topologies import topology_st from lib389._constants import DN_LDBM, DN_DM, DEFAULT_SUFFIX - from lib389._controls import SSSRequestControl - -from lib389.idm.user import UserAccounts +from lib389.idm.user import UserAccount, UserAccounts from lib389.idm.organization import Organization from lib389.idm.organizationalunit import OrganizationalUnit from lib389.backend import Backends - from lib389._mapped_object import DSLdapObject pytestmark = pytest.mark.tier1 @@ -45,16 +41,19 @@ NEW_SUFFIX_2 = 'ou={},{}'.format(NEW_SUFFIX_2_NAME, NEW_SUFFIX_1) NEW_BACKEND_1 = 'parent_base' NEW_BACKEND_2 = 'child_base' -HOSTNAME = socket.getfqdn() +OLD_HOSTNAME = socket.gethostname() +socket.sethostname('localhost') +HOSTNAME = socket.gethostname() IP_ADDRESS = socket.gethostbyname(HOSTNAME) - +OLD_IP_ADDRESS = socket.gethostbyname(OLD_HOSTNAME) @pytest.fixture(scope="module") def create_user(topology_st, request): """User for binding operation""" log.info('Adding user simplepaged_test') - + new_uri = topology_st.standalone.ldapuri.replace(OLD_HOSTNAME, HOSTNAME) + topology_st.standalone.ldapuri = new_uri users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX) user = users.create(properties={ 'uid': 'simplepaged_test', @@ -510,13 +509,8 @@ def test_search_with_timelimit(topology_st, create_user): finally: del_users(users_list) -#unstable or unstatus tests, skipped for now [email protected](max_runs=2, min_passes=1) [email protected]('aci_subject', - ('dns = "{}"'.format(HOSTNAME), - 'ip = "{}"'.format(IP_ADDRESS)), - ids=['fqdn','ip']) -def test_search_dns_ip_aci(topology_st, create_user, aci_subject): + +def test_search_ip_aci(topology_st, create_user): """Verify that after performing multiple simple paged searches to completion on the suffix with DNS or IP based ACI @@ -527,7 +521,7 @@ def test_search_dns_ip_aci(topology_st, create_user, aci_subject): varying number of users for the search base :steps: 1. Back up and remove all previous ACI from suffix - 2. Add an anonymous ACI for DNS check + 2. Add an anonymous ACI for IP check 3. Bind as test user 4. Search through added users with a simple paged control 5. Perform steps 4 three times in a row @@ -543,25 +537,30 @@ def test_search_dns_ip_aci(topology_st, create_user, aci_subject): 6. ACI should be successfully returned 7. Results should be the same with ACI with IP subject dn """ - - users_num = 100 + users_num = 20 page_size = 5 users_list = add_users(topology_st, users_num, DEFAULT_SUFFIX) search_flt = r'(uid=test*)' searchreq_attrlist = ['dn', 'sn'] + log.info("test_search_dns_ip_aci: HOSTNAME: " + HOSTNAME) + log.info("test_search_dns_ip_aci: IP_ADDRESS: " + IP_ADDRESS) + try: log.info('Back up current suffix ACI') acis_bck = topology_st.standalone.aci.list(DEFAULT_SUFFIX, ldap.SCOPE_BASE) log.info('Add test ACI') + bind_rule = 'ip = "{}" or ip = "::1" or ip = "{}"'.format(IP_ADDRESS, OLD_IP_ADDRESS) ACI_TARGET = '(targetattr != "userPassword")' ACI_ALLOW = '(version 3.0;acl "Anonymous access within domain"; allow (read,compare,search)' - ACI_SUBJECT = '(userdn = "ldap:///anyone") and (%s);)' % aci_subject + ACI_SUBJECT = '(userdn = "ldap:///anyone") and (%s);)' % bind_rule ACI_BODY = ensure_bytes(ACI_TARGET + ACI_ALLOW + ACI_SUBJECT) topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_REPLACE, 'aci', ACI_BODY)]) + time.sleep(.5) + log.info('Set user bind') - conn = create_user.bind(TEST_USER_PWD, uri=f'ldap://{IP_ADDRESS}:{topology_st.standalone.port}') + conn = create_user.bind(TEST_USER_PWD, uri=f'ldap://{HOSTNAME}:{topology_st.standalone.port}') log.info('Create simple paged results control instance') req_ctrl = SimplePagedResultsControl(True, size=page_size, cookie='') @@ -581,6 +580,7 @@ def test_search_dns_ip_aci(topology_st, create_user, aci_subject): topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_DELETE, 'aci', None)]) for aci in acis_bck: topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_ADD, 'aci', aci.getRawAci())]) + time.sleep(1) del_users(users_list) @@ -604,8 +604,8 @@ def test_search_multiple_paging(topology_st, create_user): 4. No error happens """ - users_num = 100 - page_size = 30 + users_num = 20 + page_size = 5 users_list = add_users(topology_st, users_num, DEFAULT_SUFFIX) search_flt = r'(uid=test*)' searchreq_attrlist = ['dn', 'sn'] @@ -660,8 +660,8 @@ def test_search_invalid_cookie(topology_st, create_user, invalid_cookie): 4. It should throw a TypeError exception """ - users_num = 100 - page_size = 50 + users_num = 20 + page_size = 5 users_list = add_users(topology_st, users_num, DEFAULT_SUFFIX) search_flt = r'(uid=test*)' searchreq_attrlist = ['dn', 'sn'] diff --git a/dirsrvtests/tests/suites/setup_ds/dscreate_test.py b/dirsrvtests/tests/suites/setup_ds/dscreate_test.py index 1245bdfc1..d83d159fc 100644 --- a/dirsrvtests/tests/suites/setup_ds/dscreate_test.py +++ b/dirsrvtests/tests/suites/setup_ds/dscreate_test.py @@ -1,12 +1,10 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2016 Red Hat, Inc. +# Copyright (C) 2021 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). # See LICENSE for details. # --- END COPYRIGHT BLOCK --- - - import sys import pytest from lib389 import DirSrv @@ -17,14 +15,12 @@ from lib389.instance.options import General2Base, Slapd2Base from lib389._constants import * from lib389.utils import ds_is_older -import tempfile - pytestmark = [pytest.mark.tier0, pytest.mark.skipif(ds_is_older('1.4.1.2'), reason="Needs a compatible systemd unit, see PR#50213")] INSTANCE_PORT = 54321 +INSTANCE_SECURE_PORT = 54322 INSTANCE_SERVERID = 'standalone' - DEBUGGING = True MAJOR, MINOR, _, _, _ = sys.version_info @@ -75,6 +71,7 @@ def test_setup_ds_minimal_dry(topology): slapd_options = Slapd2Base(lc.log) slapd_options.set('instance_name', INSTANCE_SERVERID) slapd_options.set('port', INSTANCE_PORT) + slapd_options.set('secure_port', INSTANCE_SECURE_PORT) slapd_options.set('root_password', PW_DM) slapd_options.verify() slapd = slapd_options.collect() @@ -102,6 +99,7 @@ def test_setup_ds_minimal(topology): slapd_options = Slapd2Base(lc.log) slapd_options.set('instance_name', INSTANCE_SERVERID) slapd_options.set('port', INSTANCE_PORT) + slapd_options.set('secure_port', INSTANCE_SECURE_PORT) slapd_options.set('root_password', PW_DM) slapd_options.verify() slapd = slapd_options.collect() @@ -117,14 +115,3 @@ def test_setup_ds_minimal(topology): topology.standalone.start() # Okay, actually remove the instance remove_ds_instance(topology.standalone) - - -def test_setup_ds_inf_minimal(topology): - if MAJOR < 3: - return - # Write a template inf - # Check it? - # Setup the server - - pass - diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py b/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py index 3451c08ef..2429f71fb 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py @@ -12,14 +12,10 @@ import logging import ldap import time from ldap.syncrepl import SyncreplConsumer -import pytest from lib389 import DirSrv -from lib389.idm.user import nsUserAccounts, UserAccounts +from lib389.idm.user import nsUserAccounts from lib389.topologies import topology_st as topology -from lib389.paths import Paths -from lib389.utils import ds_is_older -from lib389.plugins import RetroChangelogPlugin, ContentSyncPlugin -from lib389._constants import * +from lib389._constants import DEFAULT_SUFFIX log = logging.getLogger(__name__) @@ -76,6 +72,7 @@ class ISyncRepl(DirSrv, SyncreplConsumer): log.debug(f'syncrepl_complete -> {self.msgid}') assert self.msgid is not None # Loop until the operation is complete. + time.sleep(1) while super().syncrepl_poll(msgid=self.msgid) is True: pass assert self.next_cookie is not None diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/openldap_test.py b/dirsrvtests/tests/suites/syncrepl_plugin/openldap_test.py index 2a9e1e7fe..25a5ed3d2 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/openldap_test.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/openldap_test.py @@ -8,15 +8,12 @@ import logging import ldap import time -from ldap.syncrepl import SyncreplConsumer import pytest -from lib389 import DirSrv -from lib389.idm.user import nsUserAccounts, UserAccounts from lib389.topologies import topology_st as topology from lib389.paths import Paths from lib389.utils import ds_is_older from lib389.plugins import RetroChangelogPlugin, ContentSyncPlugin -from lib389._constants import * +from lib389._constants import ErrorLog, DEFAULT_SUFFIX from lib389.plugins import EntryUUIDPlugin from . import ISyncRepl, syncstate_assert diff --git a/docs/slapi.doxy.in b/docs/slapi.doxy.in index 8ce74bf50..5e0efe6df 100644 --- a/docs/slapi.doxy.in +++ b/docs/slapi.doxy.in @@ -1,4 +1,4 @@ -# Doxyfile 1.8.20 +# Doxyfile 1.9.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. @@ -313,7 +313,10 @@ OPTIMIZE_OUTPUT_SLICE = NO # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. +# the files are not read by doxygen. When specifying no_extension you should add +# * to the FILE_PATTERNS. +# +# Note see also the list of default file extension mappings. EXTENSION_MAPPING = @@ -523,6 +526,13 @@ EXTRACT_LOCAL_METHODS = NO EXTRACT_ANON_NSPACES = NO +# If this flag is set to YES, the name of an unnamed parameter in a declaration +# will be determined by the corresponding definition. By default unnamed +# parameters remain unnamed in the output. +# The default value is: YES. + +RESOLVE_UNNAMED_PARAMS = YES + # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation @@ -560,11 +570,18 @@ HIDE_IN_BODY_DOCS = NO INTERNAL_DOCS = NO -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES, upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# (including Cygwin) and Mac users are advised to set this option to NO. +# With the correct setting of option CASE_SENSE_NAMES doxygen will better be +# able to match the capabilities of the underlying filesystem. In case the +# filesystem is case sensitive (i.e. it supports files in the same directory +# whose names only differ in casing), the option must be set to YES to properly +# deal with such files in case they appear in the input. For filesystems that +# are not case sensitive the option should be be set to NO to properly deal with +# output files written for symbols that only differ in casing, such as for two +# classes, one named CLASS and the other named Class, and to also support +# references to files without having to specify the exact matching casing. On +# Windows (including Cygwin) and MacOS, users should typically set this option +# to NO, whereas on Linux or other Unix flavors it should typically be set to +# YES. # The default value is: system dependent. CASE_SENSE_NAMES = YES @@ -803,7 +820,10 @@ WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when -# a warning is encountered. +# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS +# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but +# at the end of the doxygen process doxygen will return with a non-zero status. +# Possible values are: NO, YES and FAIL_ON_WARNINGS. # The default value is: NO. WARN_AS_ERROR = NO @@ -839,8 +859,8 @@ INPUT = src/libsds/include/sds.h # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: https://www.gnu.org/software/libiconv/) for the list of -# possible encodings. +# documentation (see: +# https://www.gnu.org/software/libiconv/) for the list of possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 @@ -853,13 +873,15 @@ INPUT_ENCODING = UTF-8 # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # +# Note the list of default checked file patterns might differ from the list of +# default file extension mappings. +# # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment), -# *.doc (to be provided as doxygen C comment), *.txt (to be provided as doxygen -# C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, -# *.vhdl, *.ucf, *.qsf and *.ice. +# *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, *.vhdl, +# *.ucf, *.qsf and *.ice. FILE_PATTERNS = @@ -1074,16 +1096,22 @@ USE_HTAGS = NO VERBATIM_HEADERS = YES # If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the -# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the -# cost of reduced performance. This can be particularly helpful with template -# rich C++ code for which doxygen's built-in parser lacks the necessary type -# information. +# clang parser (see: +# http://clang.llvm.org/) for more accurate parsing at the cost of reduced +# performance. This can be particularly helpful with template rich C++ code for +# which doxygen's built-in parser lacks the necessary type information. # Note: The availability of this option depends on whether or not doxygen was # generated with the -Duse_libclang=ON option for CMake. # The default value is: NO. CLANG_ASSISTED_PARSING = NO +# If clang assisted parsing is enabled and the CLANG_ADD_INC_PATHS tag is set to +# YES then doxygen will add the directory of each input to the include path. +# The default value is: YES. + +CLANG_ADD_INC_PATHS = YES + # If clang assisted parsing is enabled you can provide the compiler with command # line options that you would normally use when invoking the compiler. Note that # the include paths will already be set by doxygen for the files and directories @@ -1097,7 +1125,7 @@ CLANG_OPTIONS = # file is the compilation database (see: # http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the # options used when the source files were built. This is equivalent to -# specifying the "-p" option to a clang tool, such as clang-check. These options +# specifying the -p option to a clang tool, such as clang-check. These options # will then be passed to the parser. Any options specified with CLANG_OPTIONS # will be added as well. # Note: The availability of this option depends on whether or not doxygen was @@ -1116,13 +1144,6 @@ CLANG_DATABASE_PATH = ALPHABETICAL_INDEX = YES -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored @@ -1293,10 +1314,11 @@ HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: https://developer.apple.com/xcode/), introduced with OSX -# 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in +# environment (see: +# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To +# create a documentation set, doxygen will generate a Makefile in the HTML +# output directory. Running make will produce the docset in that directory and +# running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy # genXcode/_index.html for more information. @@ -1338,8 +1360,8 @@ DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. +# (see: +# https://www.microsoft.com/en-us/download/details.aspx?id=21138) on Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML @@ -1414,7 +1436,8 @@ QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace -# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. @@ -1422,8 +1445,8 @@ QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- -# folders). +# Folders (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. @@ -1431,16 +1454,16 @@ QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom -# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- -# filters). +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- -# filters). +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = @@ -1452,9 +1475,9 @@ QHP_CUST_FILTER_ATTRS = QHP_SECT_FILTER_ATTRS = -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. +# The QHG_LOCATION tag can be used to specify the location (absolute path +# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to +# run qhelpgenerator on the generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = @@ -1581,7 +1604,7 @@ USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. +# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. @@ -1611,7 +1634,8 @@ MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# (see: +# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. @@ -1658,7 +1682,8 @@ SERVER_BASED_SEARCH = NO # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library -# Xapian (see: https://xapian.org/). +# Xapian (see: +# https://xapian.org/). # # See the section "External Indexing and Searching" for details. # The default value is: NO. @@ -1671,8 +1696,9 @@ EXTERNAL_SEARCH = NO # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library -# Xapian (see: https://xapian.org/). See the section "External Indexing and -# Searching" for details. +# Xapian (see: +# https://xapian.org/). See the section "External Indexing and Searching" for +# details. # This tag requires that the tag SEARCHENGINE is set to YES. SEARCHENGINE_URL = @@ -2351,10 +2377,32 @@ UML_LOOK = NO # but if the number exceeds 15, the total amount of fields shown is limited to # 10. # Minimum value: 0, maximum value: 100, default value: 10. -# This tag requires that the tag HAVE_DOT is set to YES. +# This tag requires that the tag UML_LOOK is set to YES. UML_LIMIT_NUM_FIELDS = 10 +# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and +# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS +# tag is set to YES, doxygen will add type and arguments for attributes and +# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen +# will not generate fields with class member information in the UML graphs. The +# class diagrams will look similar to the default class diagrams but using UML +# notation for the relationships. +# Possible values are: NO, YES and NONE. +# The default value is: NO. +# This tag requires that the tag UML_LOOK is set to YES. + +DOT_UML_DETAILS = NO + +# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters +# to display on a single line. If the actual line length exceeds this threshold +# significantly it will wrapped across multiple lines. Some heuristics are apply +# to avoid ugly line breaks. +# Minimum value: 0, maximum value: 1000, default value: 17. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_WRAP_THRESHOLD = 17 + # If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and # collaboration graphs will show the relations between templates and their # instances. @@ -2544,9 +2592,11 @@ DOT_MULTI_TARGETS = NO GENERATE_LEGEND = YES -# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot +# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate # files that are used to generate the various graphs. +# +# Note: This setting is not only used for dot files but also for msc and +# plantuml temporary files. # The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. DOT_CLEANUP = YES diff --git a/include/base/util.h b/include/base/util.h index 8ad5ddfbb..0695c4a55 100644 --- a/include/base/util.h +++ b/include/base/util.h @@ -39,7 +39,7 @@ NSPR_BEGIN_EXTERN_C NSAPI_PUBLIC int INTutil_itoa(int i, char *a); NSAPI_PUBLIC -int INTutil_vsprintf(char *s, register const char *fmt, va_list args); +int INTutil_vsprintf(char *s, const char *fmt, va_list args); NSAPI_PUBLIC int INTutil_sprintf(char *s, const char *fmt, ...) #ifdef __GNUC__ @@ -48,7 +48,7 @@ NSAPI_PUBLIC int INTutil_sprintf(char *s, const char *fmt, ...) ; #endif -NSAPI_PUBLIC int INTutil_vsnprintf(char *s, int n, register const char *fmt, va_list args); +NSAPI_PUBLIC int INTutil_vsnprintf(char *s, int n, const char *fmt, va_list args); NSAPI_PUBLIC int INTutil_snprintf(char *s, int n, const char *fmt, ...) #ifdef __GNUC__ diff --git a/ldap/servers/plugins/acl/acllas.c b/ldap/servers/plugins/acl/acllas.c index 94eea35f1..8ebb7a630 100644 --- a/ldap/servers/plugins/acl/acllas.c +++ b/ldap/servers/plugins/acl/acllas.c @@ -259,7 +259,7 @@ DS_LASIpGetter(NSErr_t *errp, PList_t subject, PList_t resource, PList_t auth_in if (rv != LAS_EVAL_TRUE || (NULL == aclpb)) { acl_print_acllib_err(errp, NULL); slapi_log_err(SLAPI_LOG_ACL, plugin_name, - "DS_LASIpGetter:Unable to get the ACLPB(%d)\n", rv); + "DS_LASIpGetter: Unable to get the ACLPB(%d)\n", rv); return LAS_EVAL_FAIL; } @@ -362,7 +362,6 @@ DS_LASDnsGetter(NSErr_t *errp, PList_t subject, PList_t resource, PList_t auth_i char buf[PR_NETDB_BUF_SIZE]; if (slapi_pblock_get(aclpb->aclpb_pblock, SLAPI_CONN_CLIENTNETADDR, &client_praddr) != 0) { - slapi_log_err(SLAPI_LOG_ERR, plugin_name, "DS_LASDnsGetter - Could not get client IP.\n"); return (LAS_EVAL_FAIL); } @@ -377,12 +376,41 @@ DS_LASDnsGetter(NSErr_t *errp, PList_t subject, PList_t resource, PList_t auth_i (*dnsList)->bv_len = strlen((*dnsList)->bv_val); slapi_pblock_set(aclpb->aclpb_pblock, SLAPI_CLIENT_DNS, &dnsList); } + } else { + char *errtext = NULL; + PRInt32 errlen; + char ip_str[1024] = {0}; + PR_NetAddrToString(&client_praddr, ip_str, 1024); + errlen = PR_GetErrorTextLength(); + if (errlen > 0) { + errtext = slapi_ch_malloc(errlen + 1); + if (PR_GetErrorText(errtext) > 0) { + slapi_log_err(SLAPI_LOG_ACL, plugin_name, "DS_LASDnsGetter - " + "Failed to resolve IP address (%s) error %d: %s\n", + ip_str, PR_GetError(), errtext); + } + slapi_ch_free_string(&errtext); + } else { + slapi_log_err(SLAPI_LOG_ACL, plugin_name, "DS_LASDnsGetter - " + "Failed to resolve IP address (%s) error %d\n", + ip_str, PR_GetError()); + } } slapi_ch_free((void **)&hp); } - if (NULL == dnsName) + if (NULL == dnsName) { + char ip_str[1024] = {0}; + PR_NetAddrToString(&client_praddr, ip_str, 1024); + slapi_log_err(SLAPI_LOG_ACL, plugin_name, + "DS_LASDnsGetter - Could not get host name from client IP (%s).\n", ip_str); return LAS_EVAL_FAIL; + } else { + char ip_str[1024] = {0}; + PR_NetAddrToString(&client_praddr, ip_str, 1024); + slapi_log_err(SLAPI_LOG_ACL, plugin_name, + "DS_LASDnsGetter - Got host name (%s) from client IP (%s).\n", dnsName, ip_str); + } rv = PListInitProp(subject, 0, ACL_ATTR_DNS, dnsName, NULL); if (rv < 0) { @@ -393,6 +421,7 @@ DS_LASDnsGetter(NSErr_t *errp, PList_t subject, PList_t resource, PList_t auth_i slapi_log_err(SLAPI_LOG_ACL, plugin_name, "DS_LASDnsGetter - DNS name: %s\n", dnsName); return LAS_EVAL_TRUE; } + /***************************************************************************/ /* New LASes */ /* */ diff --git a/src/Cargo.lock b/src/Cargo.lock index 4f2e641a8..45c534033 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -76,9 +76,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.69" +version = "1.0.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2" +checksum = "d26a6ce4b6a484fa3edb70f7efa6fc430fd2b87285fe8b84304fd0936faa0dc0" dependencies = [ "jobserver", ] @@ -106,9 +106,9 @@ dependencies = [ [[package]] name = "concread" -version = "0.2.16" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ed243b9cfff6696137dc72c9bdfa75d5954b5a6a3fa5da9ecb5388d3b0551a0" +checksum = "c874e11ba0c799d6d586ee8b0c5ad0f7444c0b8ec4e50c351a4f6417ae5bfb26" dependencies = [ "ahash", "crossbeam", @@ -269,9 +269,9 @@ dependencies = [ [[package]] name = "itoa" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" [[package]] name = "jobserver" @@ -290,9 +290,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.99" +version = "0.2.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765" +checksum = "a2a5ac8f984bfcf3a823267e5fde638acc3325f6496633a5da6bb6eb2171e103" [[package]] name = "librnsslapd" @@ -315,9 +315,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb" +checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109" dependencies = [ "scopeguard", ] @@ -362,9 +362,9 @@ dependencies = [ [[package]] name = "openssl-sys" -version = "0.9.66" +version = "0.9.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1996d2d305e561b70d1ee0c53f1542833f4e1ac6ce9a6708b6ff2738ca67dc82" +checksum = "69df2d8dfc6ce3aaf44b40dec6f487d5a886516cf6879c49e98e0710f310a058" dependencies = [ "autocfg", "cc", @@ -375,9 +375,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" dependencies = [ "instant", "lock_api", @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018" +checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" dependencies = [ "cfg-if", "instant", @@ -443,9 +443,9 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" -version = "1.0.28" +version = "1.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612" +checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d" dependencies = [ "unicode-xid", ] @@ -544,18 +544,18 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "serde" -version = "1.0.127" +version = "1.0.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f03b9878abf6d14e6779d3f24f07b2cfa90352cfec4acc5aab8f1ac7f146fae8" +checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.127" +version = "1.0.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a024926d3432516606328597e0f224a51355a493b49fdd67e9209187cbe55ecc" +checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b" dependencies = [ "proc-macro2", "quote", @@ -564,9 +564,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.66" +version = "1.0.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127" +checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8" dependencies = [ "itoa", "ryu", @@ -603,9 +603,9 @@ checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" [[package]] name = "syn" -version = "1.0.74" +version = "1.0.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c" +checksum = "c6f107db402c2c2055242dbf4d2af0e69197202e9faacbef9571bbe47f5a1b84" dependencies = [ "proc-macro2", "quote", @@ -649,9 +649,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.10.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01cf844b23c6131f624accf65ce0e4e9956a8bb329400ea5bcc26ae3a5c20b0b" +checksum = "c2c2416fdedca8443ae44b4527de1ea633af61d8f7169ffa6e72c5b53d24efcc" dependencies = [ "autocfg", "pin-project-lite", @@ -680,9 +680,9 @@ dependencies = [ [[package]] name = "unicode-width" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" [[package]] name = "unicode-xid" @@ -747,18 +747,18 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "zeroize" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "377db0846015f7ae377174787dd452e1c5f5a9050bc6f954911d01f116daa0cd" +checksum = "bf68b08513768deaa790264a7fac27a58cbf2705cfcdc9448362229217d7e970" dependencies = [ "zeroize_derive", ] [[package]] name = "zeroize_derive" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c1e130bebaeab2f23886bf9acbaca14b092408c452543c857f66399cd6dab1" +checksum = "bdff2024a851a322b08f179173ae2ba620445aef1e838f0c196820eade4ae0c7" dependencies = [ "proc-macro2", "quote", diff --git a/src/lib389/lib389/topologies.py b/src/lib389/lib389/topologies.py index fb4121003..db505535f 100644 --- a/src/lib389/lib389/topologies.py +++ b/src/lib389/lib389/topologies.py @@ -90,6 +90,7 @@ def _create_instances(topo_dict, suffix): # we'll flick this to ldaps. instance.use_ldap_uri() instance.open() + instance.config.set('nsslapd-accesslog-logbuffering','off') if role == ReplicaRole.STANDALONE: ins[instance.serverid] = instance instances.update(ins) @@ -103,7 +104,6 @@ def _create_instances(topo_dict, suffix): hs[instance.serverid] = instance instances.update(hs) if DEBUGGING: - instance.config.set('nsslapd-accesslog-logbuffering','off') instance.config.set('nsslapd-errorlog-level','8192') instance.config.set('nsslapd-accesslog-level','260') instance.config.set('nsslapd-auditlog-logging-enabled','on')
0
bacf80754cf883af96d4bd319399502a2c1e561f
389ds/389-ds-base
pass instance correctly to ds_is_older (#5903) Correctly pass instance to instance to ds_is_older when initializing PosixGroups class. Currently this results in an error when connecting to a remote 389ds instance. Fixes #5902
commit bacf80754cf883af96d4bd319399502a2c1e561f Author: markafarrell <[email protected]> Date: Wed Aug 30 22:19:11 2023 +1000 pass instance correctly to ds_is_older (#5903) Correctly pass instance to instance to ds_is_older when initializing PosixGroups class. Currently this results in an error when connecting to a remote 389ds instance. Fixes #5902 diff --git a/src/lib389/lib389/idm/group.py b/src/lib389/lib389/idm/group.py index 1b60a1f51..560a2c697 100644 --- a/src/lib389/lib389/idm/group.py +++ b/src/lib389/lib389/idm/group.py @@ -36,7 +36,7 @@ class Group(DSLdapObject): 'top', 'groupOfNames', ] - if not ds_is_older('1.3.7'): + if not ds_is_older('1.3.7', instance=instance): self._create_objectclasses.append('nsMemberOf') self._protected = False @@ -122,7 +122,7 @@ class UniqueGroup(DSLdapObject): 'top', 'groupOfUniqueNames', ] - if not ds_is_older('1.3.7'): + if not ds_is_older('1.3.7', instance=instance): self._create_objectclasses.append('nsMemberOf') self._protected = False @@ -175,11 +175,11 @@ class nsAdminGroup(DSLdapObject): 'top', 'nsAdminGroup' ] - if ds_is_older('1.3.7'): + if ds_is_older('1.3.7', instance=instance): self._create_objectclasses.append('inetUser') else: self._create_objectclasses.append('nsMemberOf') - if not ds_is_older('1.4.0'): + if not ds_is_older('1.4.0', instance=instance): self._create_objectclasses.append('nsAccount') user_compare_exclude = [ 'nsUniqueId', diff --git a/src/lib389/lib389/idm/posixgroup.py b/src/lib389/lib389/idm/posixgroup.py index d1debcf12..90fb00fb6 100644 --- a/src/lib389/lib389/idm/posixgroup.py +++ b/src/lib389/lib389/idm/posixgroup.py @@ -38,7 +38,7 @@ class PosixGroup(DSLdapObject): 'groupOfNames', 'posixGroup', ] - if not ds_is_older('1.3.7'): + if not ds_is_older('1.3.7', instance=instance): self._create_objectclasses.append('nsMemberOf') self._protected = False diff --git a/src/lib389/lib389/idm/services.py b/src/lib389/lib389/idm/services.py index d1e5b4693..0439cf8f3 100644 --- a/src/lib389/lib389/idm/services.py +++ b/src/lib389/lib389/idm/services.py @@ -38,7 +38,7 @@ class ServiceAccount(Account): 'top', 'applicationProcess', ] - if ds_is_older('1.4.0'): + if ds_is_older('1.4.0', instance=instance): # This is a HORRIBLE HACK for older versions that DON'T have # correct updated schema! # diff --git a/src/lib389/lib389/monitor.py b/src/lib389/lib389/monitor.py index c77a50c40..8f9d0001b 100644 --- a/src/lib389/lib389/monitor.py +++ b/src/lib389/lib389/monitor.py @@ -298,7 +298,7 @@ class MonitorBackend(DSLdapObject): 'currentdncachecount', 'maxdncachecount', ] - if ds_is_older("1.4.0"): + if ds_is_older("1.4.0", instance=self._instance): self._backend_keys.extend([ 'normalizeddncachetries', 'normalizeddncachehits', diff --git a/src/lib389/lib389/replica.py b/src/lib389/lib389/replica.py index e899ed45f..e89664eef 100644 --- a/src/lib389/lib389/replica.py +++ b/src/lib389/lib389/replica.py @@ -1140,7 +1140,7 @@ class Changelog5(DSLdapObject): 'top', 'nsChangelogConfig', ] - if ds_is_older('1.4.0'): + if ds_is_older('1.4.0', instance=instance): self._create_objectclasses = [ 'top', 'extensibleobject', @@ -1217,7 +1217,7 @@ class Replica(DSLdapObject): 'top', 'nsds5Replica' ] - if ds_is_older('1.4.0'): + if ds_is_older('1.4.0', instance=instance): self._create_objectclasses.append('extensibleobject') self._protected = False self._suffix = None @@ -1906,7 +1906,7 @@ class BootstrapReplicationManager(DSLdapObject): 'netscapeServer', # for cn 'nsAccount', # for authentication attributes ] - if ds_is_older('1.4.0'): + if ds_is_older('1.4.0', instance=instance): self._create_objectclasses.remove('nsAccount') self._protected = False self.common_name = 'replication manager' diff --git a/src/lib389/lib389/schema.py b/src/lib389/lib389/schema.py index b3aa67f87..f3dc5f4c5 100755 --- a/src/lib389/lib389/schema.py +++ b/src/lib389/lib389/schema.py @@ -295,7 +295,7 @@ class Schema(DSLdapObject): file_list = [] file_list += glob.glob(os.path.join(self.conn.schemadir, "*.ldif")) - if ds_is_newer('1.3.6.0'): + if ds_is_newer('1.3.6.0', instance=self._instance): file_list += glob.glob(os.path.join(self.conn.ds_paths.system_schema_dir, "*.ldif")) return file_list @@ -567,7 +567,7 @@ class SchemaLegacy(object): """return a list of the schema files in the instance schemadir""" file_list = [] file_list += glob.glob(self.conn.schemadir + "/*.ldif") - if ds_is_newer('1.3.6.0'): + if ds_is_newer('1.3.6.0', instance=self._instance): file_list += glob.glob(self.conn.ds_paths.system_schema_dir + "/*.ldif") return file_list
0
454ee60f42d6e20cc2b3f1a1397880f9bd66812e
389ds/389-ds-base
Issue 5834 - AccountPolicyPlugin erroring for some users (#5866) Bug Description: With the account policy plugin enabled and lastloginhistory size set to non 0 an issue occurs during simultaneous binds of the same user. In this case the timestamp to be stored in the lastloginHistory attribute already exists from a previous bind, and generates an error message. A side effect of lastloginHistory feature is that the modifytimestamp value is updated after a successful bind, even when the feature is disabled. Fix Description: Before a timestamp is added to the lastloginHistory attribute a check is performed to make sure it doesnt already exist. Ensure the entry is not modified when this feature is disabled. Fixes: https://github.com/389ds/389-ds-base/issues/5834 Relates:https://github.com/389ds/389-ds-base/issues/5752 Reviewed by: @progier389, @tbordaz (Thank you)
commit 454ee60f42d6e20cc2b3f1a1397880f9bd66812e Author: James Chapman <[email protected]> Date: Tue Aug 8 12:35:27 2023 +0000 Issue 5834 - AccountPolicyPlugin erroring for some users (#5866) Bug Description: With the account policy plugin enabled and lastloginhistory size set to non 0 an issue occurs during simultaneous binds of the same user. In this case the timestamp to be stored in the lastloginHistory attribute already exists from a previous bind, and generates an error message. A side effect of lastloginHistory feature is that the modifytimestamp value is updated after a successful bind, even when the feature is disabled. Fix Description: Before a timestamp is added to the lastloginHistory attribute a check is performed to make sure it doesnt already exist. Ensure the entry is not modified when this feature is disabled. Fixes: https://github.com/389ds/389-ds-base/issues/5834 Relates:https://github.com/389ds/389-ds-base/issues/5752 Reviewed by: @progier389, @tbordaz (Thank you) diff --git a/ldap/servers/plugins/acctpolicy/acct_plugin.c b/ldap/servers/plugins/acctpolicy/acct_plugin.c index 83a42786c..ba9705f74 100644 --- a/ldap/servers/plugins/acctpolicy/acct_plugin.c +++ b/ldap/servers/plugins/acctpolicy/acct_plugin.c @@ -198,6 +198,7 @@ acct_update_login_history(const char *dn, char *timestr) void *plugin_id = NULL; int rc = -1; int num_entries = 0; + int mod_required = 0; size_t i = 0; char **login_hist = NULL; Slapi_PBlock *entry_pb = NULL; @@ -208,75 +209,100 @@ acct_update_login_history(const char *dn, char *timestr) LDAPMod attribute; LDAPMod *list_of_mods[2]; - plugin_id = get_identity(); + /* nothing to do if timestr is empty */ + if (!timestr) { + return (rc); + } + plugin_id = get_identity(); sdn = slapi_sdn_new_normdn_byref(dn); slapi_search_get_entry(&entry_pb, sdn, NULL, &e, plugin_id); + slapi_sdn_free(&sdn); - if (!timestr) { + /* if the entry doesn't exist, just return */ + if (e == NULL) { return (rc); } config_rd_lock(); cfg = get_config(); + /* does this value already exist in the entry */ + Slapi_Value *timestr_val = slapi_value_new(); + slapi_value_set_string(timestr_val, timestr); + if (slapi_entry_attr_has_syntax_value(e, cfg->login_history_attr, timestr_val)) { + slapi_search_get_entry_done(&entry_pb); + slapi_value_free(&timestr_val); + config_unlock(); + return 0; + } + slapi_value_free(&timestr_val); - /* history size of zero disables login history */ - if (cfg->login_history_size) { - /* get login history */ - login_hist = slapi_entry_attr_get_charray_ext(e, cfg->login_history_attr, &num_entries); - - /* first time round */ - if (!login_hist || !num_entries) { - login_hist = (char **)slapi_ch_calloc(2, sizeof(char *)); - } - - /* Do we need to resize login_hist array */ + /* now we have an entry that doesnt contain the current timestr */ + login_hist = slapi_entry_attr_get_charray_ext(e, cfg->login_history_attr, &num_entries); + if (login_hist && num_entries) { + /* do we need to trim the array */ if (num_entries >= cfg->login_history_size) { + /* free values we dont want */ int diff = (num_entries - cfg->login_history_size); - /* free times we dont need */ for (i = 0; i <= diff; i++) { slapi_ch_free_string(&login_hist[i]); } - /* remap array*/ - for (i = 0; i < (cfg->login_history_size - 1); i++) { - login_hist[i] = login_hist[(diff + 1) + i]; + /* remap array if it exists */ + for (i = 0; i < cfg->login_history_size; i++) { + login_hist[i] = login_hist[diff + (i + 1)]; + } + if (cfg->login_history_size != 0) { + /* append latest value */ + login_hist[i - 1] = slapi_ch_smprintf("%s", timestr); + login_hist[i] = NULL; + mod_required = 1; + } else { + /* size is 0 and array has been trimmed, we need a mod */ + mod_required = 1; } - /* expand array and add current time string at the end */ - login_hist = (char **)slapi_ch_realloc((char *)login_hist, sizeof(char *) * (cfg->login_history_size + 1)); - login_hist[i] = slapi_ch_smprintf("%s", timestr); - login_hist[i + 1] = NULL; } else { - /* expand array and add current time string at the end */ - login_hist = (char **)slapi_ch_realloc((char *)login_hist, sizeof(char *) * (num_entries + 2)); - login_hist[num_entries] = slapi_ch_smprintf("%s", timestr); - login_hist[num_entries + 1] = NULL; + if (cfg->login_history_size != 0) { + /* realloc and append latest value */ + login_hist = (char **)slapi_ch_realloc((char *)login_hist, sizeof(char *) * (num_entries + 2)); + login_hist[num_entries] = slapi_ch_smprintf("%s", timestr); + login_hist[num_entries + 1] = NULL; + mod_required = 1; + } } + /* first time round */ + } else if (cfg->login_history_size > 0) { + login_hist = (char **)slapi_ch_calloc(2, sizeof(char *)); + /* alloc new array and append latest value */ + login_hist = (char **)slapi_ch_realloc((char *)login_hist, sizeof(char *) * (num_entries + 2)); + login_hist[num_entries] = slapi_ch_smprintf("%s", timestr); + login_hist[num_entries + 1] = NULL; + mod_required = 1; } - /* modify the attribute */ - attribute.mod_type = cfg->login_history_attr; - attribute.mod_op = LDAP_MOD_REPLACE; - attribute.mod_values = login_hist; - - list_of_mods[0] = &attribute; - list_of_mods[1] = NULL; - - mod_pb = slapi_pblock_new(); - slapi_modify_internal_set_pb(mod_pb, dn, list_of_mods, NULL, NULL, plugin_id, 0); - slapi_modify_internal_pb(mod_pb); - slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &rc); - if (rc != LDAP_SUCCESS) { - slapi_log_err(SLAPI_LOG_ERR, "acct_update_login_history", "Modify error %d on entry '%s'\n", rc, dn); + if (mod_required) { + /* modify the attribute */ + attribute.mod_type = cfg->login_history_attr; + attribute.mod_op = LDAP_MOD_REPLACE; + attribute.mod_values = login_hist; + + list_of_mods[0] = &attribute; + list_of_mods[1] = NULL; + + mod_pb = slapi_pblock_new(); + slapi_modify_internal_set_pb(mod_pb, dn, list_of_mods, NULL, NULL, plugin_id, 0); + slapi_modify_internal_pb(mod_pb); + slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &rc); + if (rc != LDAP_SUCCESS) { + slapi_log_err(SLAPI_LOG_ERR, "acct_update_login_history", "Modify error %d on entry '%s'\n", rc, dn); + } + slapi_pblock_destroy(mod_pb); } config_unlock(); - slapi_ch_array_free(login_hist); slapi_search_get_entry_done(&entry_pb); - slapi_sdn_free(&sdn); - slapi_pblock_destroy(mod_pb); - slapi_pblock_destroy(entry_pb); + slapi_value_free(&timestr_val); return (rc); }
0
f50e8ec950980af70d892cc45eac07684d6721a5
389ds/389-ds-base
Ticket #48755 - moving an entry could make the online init fail Bug Description: Online init (aka Total update, bulk import) scans the primary id2entry db in the order of ID. If Entry A is moved under a new superior Entry B which was generated after Entry A, when Entry A is sent to a consumer using online init, its parent entry does not exist on the consumer and the online init fails. Fix Description: - Added a command BACK_INFO_IS_ENTRYRDN to slapi_back_get_info, which returns the status of entryrdn switch maintained in the backend. - If slapi_backend_get_info(BACK_INFO_IS_ENTRYRDN) returns true for the replicated backend, repl5_tot_run searches the entry with the filter: (parentid>=1) instead of: (|(objectclass=ldapsubentry)(objectclass=nstombstone)(nsuniqueid=*))". The filter MUST be this single range filter since the IDList created for this bulk-import is not sorted by ID, but in the order of parentid. - Added a new flag OP_FLAG_BULK_IMPORT to the operation. Setting the flag implies to skip the internal operations such as eliminating ldapsubentry from the search results or a filter check. - In addition, idl_new_range_fetch is modified so that ... * A range search for parentid ignores nsslapd-idlistscanlimit by setting SLAPI_OP_RANGE_NO_ALLIDS as well as it skips sorting the IDlist by ID by setting SLAPI_OP_RANGE_NO_IDL_SORT. * In case SLAPI_OP_RANGE_NO_IDL_SORT is set, idl_new_range_fetch checks whether the key (in this case parentid) is in the IDlist. If it exists, the ID is appended. If it does not, the ID is in the leftover list and appended when the parent ID is found in the IDlist. - Increased the version of rdn-format-# in DBVERSION to 3. - Upgrade script 91reindex.pl.in is added which reindex the parentid index file in the integer order if the version of rdn-format-# in DBVERSION is less than 3. - Notes: In case entryrdn is used (nsslapd-subtree-rename-switch: on), all the type of entries including the tombstone entry and the ldap- subentry are indexed with parentid. - Another notes: This special treatment is enabled only when nsslapd- subtree-rename-switch is on. If entrydn is used instead of entryrdn, there is no possibility to establish the order that child comes first. Plus, to replace nsslapd-subtree-rename-switch on with off, the main db file id2entry.db needs to be recreated so that each entry stores DN in it. It requires export then import, which corrects the order of the entries and the order problem disappears. https://fedorahosted.org/389/ticket/48755 Reviewed by mreynolds@redhat and [email protected] (Thank you, Mark and William!!) Also, thanks to [email protected] and [email protected] for their discussion!
commit f50e8ec950980af70d892cc45eac07684d6721a5 Author: Noriko Hosoi <[email protected]> Date: Mon Jun 27 22:33:40 2016 -0700 Ticket #48755 - moving an entry could make the online init fail Bug Description: Online init (aka Total update, bulk import) scans the primary id2entry db in the order of ID. If Entry A is moved under a new superior Entry B which was generated after Entry A, when Entry A is sent to a consumer using online init, its parent entry does not exist on the consumer and the online init fails. Fix Description: - Added a command BACK_INFO_IS_ENTRYRDN to slapi_back_get_info, which returns the status of entryrdn switch maintained in the backend. - If slapi_backend_get_info(BACK_INFO_IS_ENTRYRDN) returns true for the replicated backend, repl5_tot_run searches the entry with the filter: (parentid>=1) instead of: (|(objectclass=ldapsubentry)(objectclass=nstombstone)(nsuniqueid=*))". The filter MUST be this single range filter since the IDList created for this bulk-import is not sorted by ID, but in the order of parentid. - Added a new flag OP_FLAG_BULK_IMPORT to the operation. Setting the flag implies to skip the internal operations such as eliminating ldapsubentry from the search results or a filter check. - In addition, idl_new_range_fetch is modified so that ... * A range search for parentid ignores nsslapd-idlistscanlimit by setting SLAPI_OP_RANGE_NO_ALLIDS as well as it skips sorting the IDlist by ID by setting SLAPI_OP_RANGE_NO_IDL_SORT. * In case SLAPI_OP_RANGE_NO_IDL_SORT is set, idl_new_range_fetch checks whether the key (in this case parentid) is in the IDlist. If it exists, the ID is appended. If it does not, the ID is in the leftover list and appended when the parent ID is found in the IDlist. - Increased the version of rdn-format-# in DBVERSION to 3. - Upgrade script 91reindex.pl.in is added which reindex the parentid index file in the integer order if the version of rdn-format-# in DBVERSION is less than 3. - Notes: In case entryrdn is used (nsslapd-subtree-rename-switch: on), all the type of entries including the tombstone entry and the ldap- subentry are indexed with parentid. - Another notes: This special treatment is enabled only when nsslapd- subtree-rename-switch is on. If entrydn is used instead of entryrdn, there is no possibility to establish the order that child comes first. Plus, to replace nsslapd-subtree-rename-switch on with off, the main db file id2entry.db needs to be recreated so that each entry stores DN in it. It requires export then import, which corrects the order of the entries and the order problem disappears. https://fedorahosted.org/389/ticket/48755 Reviewed by mreynolds@redhat and [email protected] (Thank you, Mark and William!!) Also, thanks to [email protected] and [email protected] for their discussion! diff --git a/Makefile.am b/Makefile.am index a0ba4b61c..ed3d46205 100644 --- a/Makefile.am +++ b/Makefile.am @@ -841,7 +841,8 @@ update_DATA = ldap/admin/src/scripts/exampleupdate.pl \ ldap/admin/src/scripts/50AES-pbe-plugin.ldif\ ldap/admin/src/scripts/50updateconfig.ldif \ ldap/admin/src/scripts/52updateAESplugin.pl \ - ldap/admin/src/scripts/dnaplugindepends.ldif + ldap/admin/src/scripts/dnaplugindepends.ldif \ + ldap/admin/src/scripts/91reindex.pl update_SCRIPTS = ldap/admin/src/scripts/exampleupdate.sh diff --git a/Makefile.in b/Makefile.in index 0c0176b38..8109469ec 100644 --- a/Makefile.in +++ b/Makefile.in @@ -2259,7 +2259,8 @@ update_DATA = ldap/admin/src/scripts/exampleupdate.pl \ ldap/admin/src/scripts/50AES-pbe-plugin.ldif\ ldap/admin/src/scripts/50updateconfig.ldif \ ldap/admin/src/scripts/52updateAESplugin.pl \ - ldap/admin/src/scripts/dnaplugindepends.ldif + ldap/admin/src/scripts/dnaplugindepends.ldif \ + ldap/admin/src/scripts/91reindex.pl update_SCRIPTS = ldap/admin/src/scripts/exampleupdate.sh diff --git a/ldap/admin/src/scripts/91reindex.pl.in b/ldap/admin/src/scripts/91reindex.pl.in new file mode 100644 index 000000000..c861f64cf --- /dev/null +++ b/ldap/admin/src/scripts/91reindex.pl.in @@ -0,0 +1,103 @@ +use Mozilla::LDAP::Conn; +use Mozilla::LDAP::Utils qw(normalizeDN); +use Mozilla::LDAP::API qw(:constant ldap_url_parse ldap_explode_dn); +use DSUpdate qw(isOffline); + +sub runinst { + my ($inf, $inst, $dseldif, $conn) = @_; + my $rc, @errs; + + # List of index to be reindexed + my @toreindex = qw(parentid); + # rdn-format value. See $rdn_format set below. + # If equal to or greater than this value, no need to reindex. + # If it needs to be unconditionally reindexed, set 0. + my @rdnconditions = (4) + + my $config = $conn->search("cn=config", "base", "(objectclass=*)"); + if (!$config) { + push @errs, ['error_finding_config_entry', 'cn=config', + $conn->getErrorString()]; + return @errs; + } + + ($rc, @errs) = isOffline($inf, $inst, $conn); + if (!$rc) { + return @errs; + } + + my $reindex = "@sbindir@/db2index -Z $inst"; + my @errs; + my $instconf = $conn->search("cn=ldbm database,cn=plugins,cn=config", "onelevel", "(objectclass=*)"); + if (!$instconf) { + push @errs, ['error_finding_config_entry', 'cn=*,cn=ldbm database,cn=plugins,cn=config', $conn->getErrorString()]; + return @errs; + } + + my $dbconf = $conn->search("cn=config,cn=ldbm database,cn=plugins,cn=config", "base", "(objectclass=*)"); + if (!$dbconf) { + push @errs, ['error_finding_config_entry', + 'cn=config,cn=ldbm database,cn=plugins,cn=config', + $conn->getErrorString()]; + return @errs; + } + + # Get the value of nsslapd-subtree-rename-switch. + my $switch = $dbconf->getValues('nsslapd-subtree-rename-switch'); + if ("" eq $switch) { + return (); # subtree-rename-switch does not exist; do nothing. + } elsif ("off" eq $switch || "OFF" eq $switch) { + return (); # subtree-rename-switch is OFF; do nothing. + } + + my $dbdir = $dbconf->getValues('nsslapd-directory'); + my $dbversion0 = $dbdir . "/DBVERSION"; + my $rdn_format = 0; + my $dbversionstr = ""; + if (!open(DBVERSION, "$dbversion0")) { + push @errs, ['error_opening_file', $dbversion0, $!]; + return @errs; + } else { + while (<DBVERSION>) { + if ($_ =~ /rdn-format/) { + $rdn_format = 1; + $dbversionstr = $_; + if ($_ =~ /rdn-format-1/) { + $rdn_format = 2; + } elsif ($_ =~ /rdn-format-2/) { + $rdn_format = 3; + } elsif ($_ =~ /rdn-format-3/) { + $rdn_format = 4; + } elsif ($_ =~ /rdn-format-4/) { + $rdn_format = 5; + } elsif ($_ =~ /rdn-format-5/) { + $rdn_format = 6; + } elsif ($_ =~ /rdn-format-/) { + # assume greater than -5 + $rdn_format = 7; + } + } + } + close DBVERSION; + } + + while ($instconf) { + my $backend= $instconf->getValues('cn'); + if (($backend eq "config") || ($backend eq "monitor")) { + goto NEXT; + } + + for (my $idx = 0; $ <= $#toreindex; $idx++) { + if (0 == $rdnconditions[$idx] || $rdnconditions[$idx] > $rdn_format) { + my $rc = system("$reindex -n $backend -t $idx"); + if ($rc) { + push @errs, ["error_reindexng", $idx, $backend, $rc]; + } + } + } +NEXT: + $instconf = $conn->nextEntry(); + } + + return @errs; +} diff --git a/ldap/admin/src/scripts/91subtreereindex.pl b/ldap/admin/src/scripts/91subtreereindex.pl index a031cc1a4..c4b40a3de 100644 --- a/ldap/admin/src/scripts/91subtreereindex.pl +++ b/ldap/admin/src/scripts/91subtreereindex.pl @@ -51,14 +51,18 @@ sub runinst { if ($_ =~ /rdn-format-1/) { $is_rdn_format = 2; } - if ($_ =~ /rdn-format-2/) { + elsif ($_ =~ /rdn-format-2/) { $is_rdn_format = 3; } + elsif ($_ =~ /rdn-format-/) { + # assume greater than -2 + $is_rdn_format = 4; + } } } close DBVERSION; - if (3 == $is_rdn_format) { + if (3 <= $is_rdn_format) { return (); # DB already has the new rdn format. } diff --git a/ldap/admin/src/scripts/setup-ds.res.in b/ldap/admin/src/scripts/setup-ds.res.in index fa3756766..e46b8583d 100644 --- a/ldap/admin/src/scripts/setup-ds.res.in +++ b/ldap/admin/src/scripts/setup-ds.res.in @@ -209,3 +209,4 @@ error_opening_file = Opening file '%s' failed. Error: %s\n error_format_error = '%s' has invalid format.\n error_update_not_offline = Error: offline mode selected but the server [%s] is still running.\n error_update_all = Failed to update all the Directory Server instances.\n +error_reindexing = Failed to reindex '%s' in backend '%s'. Error: %s\n diff --git a/ldap/ldif/template-dse.ldif.in b/ldap/ldif/template-dse.ldif.in index f18c08248..46b416bd1 100644 --- a/ldap/ldif/template-dse.ldif.in +++ b/ldap/ldif/template-dse.ldif.in @@ -930,6 +930,7 @@ objectclass: nsIndex cn: parentid nssystemindex: true nsindextype: eq +nsmatchingrule: integerOrderingMatch dn: cn=seeAlso,cn=default indexes, cn=config,cn=ldbm database,cn=plugins,cn=config objectclass: top diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index 7655ac40a..59d3374e6 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -405,12 +405,12 @@ replica_config_modify (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* { if (apply_mods) replica_set_precise_purging(r, 0); - } + } else if (strcasecmp (config_attr, type_replicaReleaseTimeout) == 0 ) { if (apply_mods) replica_set_release_timeout(r, 0); - } + } else { *returncode = LDAP_UNWILLING_TO_PERFORM; @@ -572,8 +572,7 @@ replica_config_modify (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* { if (apply_mods) { - if (apply_mods && config_attr_value[0]) - { + if (config_attr_value[0]) { PRUint64 on_off = 0; if (strcasecmp(config_attr_value, "on") == 0){ @@ -592,7 +591,7 @@ replica_config_modify (Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Entry* break; } replica_set_precise_purging(r, on_off); - } else if (apply_mods) { + } else { replica_set_precise_purging(r, 0); } } diff --git a/ldap/servers/plugins/replication/repl5_tot_protocol.c b/ldap/servers/plugins/replication/repl5_tot_protocol.c index d0c4402d1..aac89bd36 100644 --- a/ldap/servers/plugins/replication/repl5_tot_protocol.c +++ b/ldap/servers/plugins/replication/repl5_tot_protocol.c @@ -323,6 +323,10 @@ repl5_tot_run(Private_Repl_Protocol *prp) int init_retry = 0; Replica *replica; ReplicaId rid = 0; /* Used to create the replica keep alive subentry */ + Slapi_Entry *suffix = NULL; + char **instances = NULL; + Slapi_Backend *be = NULL; + int is_entryrdn = 0; PR_ASSERT(NULL != prp); @@ -354,21 +358,21 @@ retry: */ if (rc != ACQUIRE_SUCCESS) { - int optype, ldaprc, wait_retry; - conn_get_error(prp->conn, &optype, &ldaprc); - if (rc == ACQUIRE_TRANSIENT_ERROR && INIT_RETRY_MAX > init_retry++) { - wait_retry = init_retry * INIT_RETRY_INT; - slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " - "acquire replica for total update, error: %d," + int optype, ldaprc, wait_retry; + conn_get_error(prp->conn, &optype, &ldaprc); + if (rc == ACQUIRE_TRANSIENT_ERROR && INIT_RETRY_MAX > init_retry++) { + wait_retry = init_retry * INIT_RETRY_INT; + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " + "acquire replica for total update, error: %d," " retrying in %d seconds.\n", - ldaprc, wait_retry); - DS_Sleep(PR_SecondsToInterval(wait_retry)); - goto retry; - } else { - agmt_set_last_init_status(prp->agmt, ldaprc, - prp->last_acquire_response_code, 0, NULL); - goto done; - } + ldaprc, wait_retry); + DS_Sleep(PR_SecondsToInterval(wait_retry)); + goto retry; + } else { + agmt_set_last_init_status(prp->agmt, ldaprc, + prp->last_acquire_response_code, 0, NULL); + goto done; + } } else if (prp->terminate) { @@ -405,48 +409,121 @@ retry: and that the order implies that perent entry is always ahead of the child entry in the list. Otherwise, the consumer would not be properly updated because bulk import at the moment skips orphand entries. */ - /* XXXggood above assumption may not be valid if orphaned entry moved???? */ + /* XXXggood above assumption may not be valid if orphaned entry moved???? */ agmt_set_last_init_status(prp->agmt, 0, 0, 0, "Total update in progress"); slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Beginning total update of replica " - "\"%s\".\n", agmt_get_long_name(prp->agmt)); + "\"%s\".\n", agmt_get_long_name(prp->agmt)); /* RMREPL - need to send schema here */ pb = slapi_pblock_new (); - /* we need to provide managedsait control so that referral entries can - be replicated */ - ctrls = (LDAPControl **)slapi_ch_calloc (3, sizeof (LDAPControl *)); - ctrls[0] = create_managedsait_control (); - ctrls[1] = create_backend_control(area_sdn); + replica = (Replica*) object_get_data(prp->replica_object); + /* + * Get the info about the entryrdn vs. entrydn from the backend. + * If NOT is_entryrdn, its ancestor entries are always found prior to an entry. + */ + rc = slapi_lookup_instance_name_by_suffix((char *)slapi_sdn_get_dn(area_sdn), NULL, &instances, 1); + if (rc || !instances) { + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " + "get the instance name for the suffix \"%s\".\n", slapi_sdn_get_dn(area_sdn)); + goto done; + } + be = slapi_be_select_by_instance_name(instances[0]); + if (!be) { + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " + "get the instance for the suffix \"%s\".\n", slapi_sdn_get_dn(area_sdn)); + goto done; + } + rc = slapi_back_get_info(be, BACK_INFO_IS_ENTRYRDN, (void **)&is_entryrdn); + if (is_entryrdn) { + /* + * Supporting entries out of order -- parent could have a larger id than its children. + * Entires are retireved sorted by parentid without the allid threshold. + */ + /* Get suffix */ + rc = slapi_search_internal_get_entry(area_sdn, NULL, &suffix, repl_get_plugin_identity(PLUGIN_MULTIMASTER_REPLICATION)); + if (rc) { + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " + "get the suffix entry \"%s\".\n", slapi_sdn_get_dn(area_sdn)); + goto done; + } - /* Time to make sure it exists a keep alive subentry for that replica */ - replica = (Replica*) object_get_data(prp->replica_object); - if (replica) - { - rid = replica_get_rid(replica); - } - replica_subentry_check(area_sdn, rid); - - slapi_search_internal_set_pb (pb, slapi_sdn_get_dn (area_sdn), - LDAP_SCOPE_SUBTREE, "(|(objectclass=ldapsubentry)(objectclass=nstombstone)(nsuniqueid=*))", NULL, 0, ctrls, NULL, - repl_get_plugin_identity (PLUGIN_MULTIMASTER_REPLICATION), 0); - - cb_data.prp = prp; - cb_data.rc = 0; - cb_data.num_entries = 0UL; - cb_data.sleep_on_busy = 0UL; - cb_data.last_busy = current_time (); - cb_data.flowcontrol_detection = 0; - cb_data.lock = PR_NewLock(); - - /* This allows during perform_operation to check the callback data - * especially to do flow contol on delta send msgid / recv msgid - */ - conn_set_tot_update_cb(prp->conn, (void *) &cb_data); + cb_data.prp = prp; + cb_data.rc = 0; + cb_data.num_entries = 1UL; + cb_data.sleep_on_busy = 0UL; + cb_data.last_busy = current_time (); + cb_data.flowcontrol_detection = 0; + cb_data.lock = PR_NewLock(); + + /* This allows during perform_operation to check the callback data + * especially to do flow contol on delta send msgid / recv msgid + */ + conn_set_tot_update_cb(prp->conn, (void *) &cb_data); + + /* Send suffix first. */ + rc = send_entry(suffix, (void *)&cb_data); + if (rc) { + slapi_log_error(SLAPI_LOG_FATAL, repl_plugin_name, "Warning: unable to " + "send the suffix entry \"%s\" to the consumer.\n", slapi_sdn_get_dn(area_sdn)); + goto done; + } + + /* we need to provide managedsait control so that referral entries can + be replicated */ + ctrls = (LDAPControl **)slapi_ch_calloc (3, sizeof (LDAPControl *)); + ctrls[0] = create_managedsait_control (); + ctrls[1] = create_backend_control(area_sdn); + + /* Time to make sure it exists a keep alive subentry for that replica */ + if (replica) + { + rid = replica_get_rid(replica); + } + replica_subentry_check(area_sdn, rid); + /* Send the subtree of the suffix in the order of parentid index plus ldapsubentry and nstombstone. */ + slapi_search_internal_set_pb(pb, slapi_sdn_get_dn (area_sdn), + LDAP_SCOPE_SUBTREE, "(parentid>=1)", NULL, 0, ctrls, NULL, + repl_get_plugin_identity (PLUGIN_MULTIMASTER_REPLICATION), OP_FLAG_BULK_IMPORT); + cb_data.num_entries = 0UL; + } else { + /* Original total update */ + /* we need to provide managedsait control so that referral entries can + be replicated */ + ctrls = (LDAPControl **)slapi_ch_calloc (3, sizeof (LDAPControl *)); + ctrls[0] = create_managedsait_control (); + ctrls[1] = create_backend_control(area_sdn); + + /* Time to make sure it exists a keep alive subentry for that replica */ + replica = (Replica*) object_get_data(prp->replica_object); + if (replica) + { + rid = replica_get_rid(replica); + } + replica_subentry_check(area_sdn, rid); + + slapi_search_internal_set_pb (pb, slapi_sdn_get_dn (area_sdn), + LDAP_SCOPE_SUBTREE, "(|(objectclass=ldapsubentry)(objectclass=nstombstone)(nsuniqueid=*))", NULL, 0, ctrls, NULL, + repl_get_plugin_identity (PLUGIN_MULTIMASTER_REPLICATION), 0); + + cb_data.prp = prp; + cb_data.rc = 0; + cb_data.num_entries = 0UL; + cb_data.sleep_on_busy = 0UL; + cb_data.last_busy = current_time (); + cb_data.flowcontrol_detection = 0; + cb_data.lock = PR_NewLock(); + + /* This allows during perform_operation to check the callback data + * especially to do flow contol on delta send msgid / recv msgid + */ + conn_set_tot_update_cb(prp->conn, (void *) &cb_data); + } + /* Before we get started on sending entries to the replica, we need to * setup things for async propagation: * 1. Create a thread that will read the LDAP results from the connection. @@ -470,7 +547,7 @@ retry: slapi_search_internal_callback_pb (pb, &cb_data /* callback data */, get_result /* result callback */, send_entry /* entry callback */, - NULL /* referral callback*/); + NULL /* referral callback*/); /* * After completing the sending operation (or optionally failing), we need to clean up diff --git a/ldap/servers/slapd/back-ldbm/back-ldbm.h b/ldap/servers/slapd/back-ldbm/back-ldbm.h index 949929205..2d77a8aec 100644 --- a/ldap/servers/slapd/back-ldbm/back-ldbm.h +++ b/ldap/servers/slapd/back-ldbm/back-ldbm.h @@ -132,7 +132,7 @@ typedef unsigned short u_int16_t; #define BDB_BACKEND "libback-ldbm" /* This backend plugin */ #define BDB_NEWIDL "newidl" /* new idl format */ #define BDB_RDNFORMAT "rdn-format" /* Subtree rename enabled */ -#define BDB_RDNFORMAT_VERSION "2" /* rdn-format version (by default, 0) */ +#define BDB_RDNFORMAT_VERSION "3" /* rdn-format version (by default, 0) */ #define BDB_DNFORMAT "dn-4514" /* DN format RFC 4514 compliant */ #define BDB_DNFORMAT_VERSION "1" /* DN format version */ @@ -808,11 +808,11 @@ typedef struct _back_search_result_set /* #define LDBM_ENTRYRDN_OID "2.16.840.1.113730.3.1.2097" */ #define LDBM_ANCESTORID_STR "ancestorid" -#define LDBM_ENTRYDN_STR "entrydn" +#define LDBM_ENTRYDN_STR SLAPI_ATTR_ENTRYDN #define LDBM_ENTRYRDN_STR "entryrdn" #define LDBM_NUMSUBORDINATES_STR "numsubordinates" #define LDBM_TOMBSTONE_NUMSUBORDINATES_STR "tombstonenumsubordinates" -#define LDBM_PARENTID_STR "parentid" +#define LDBM_PARENTID_STR SLAPI_ATTR_PARENTID /* Name of psuedo attribute used to track default indexes */ #define LDBM_PSEUDO_ATTR_DEFAULT ".default" diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index bc290cb2e..93d42bed8 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -7315,6 +7315,11 @@ ldbm_back_get_info(Slapi_Backend *be, int cmd, void **info) } break; } + case BACK_INFO_IS_ENTRYRDN: + { + *(int *)info = entryrdn_get_switch(); + break; + } default: break; } diff --git a/ldap/servers/slapd/back-ldbm/filterindex.c b/ldap/servers/slapd/back-ldbm/filterindex.c index 9c14de421..e87cf308e 100644 --- a/ldap/servers/slapd/back-ldbm/filterindex.c +++ b/ldap/servers/slapd/back-ldbm/filterindex.c @@ -552,6 +552,8 @@ range_candidates( struct berval *low = NULL, *high = NULL; struct berval **lows = NULL, **highs = NULL; back_txn txn = {NULL}; + int operator = 0; + Operation *op = NULL; LDAPDebug(LDAP_DEBUG_TRACE, "=> range_candidates attr=%s\n", type, 0, 0); @@ -579,17 +581,24 @@ range_candidates( high = attr_value_lowest(highs, slapi_berval_cmp); } + /* Check if it is for bulk import. */ + slapi_pblock_get(pb, SLAPI_OPERATION, &op); + if (entryrdn_get_switch() && operation_is_flag_set(op, OP_FLAG_INTERNAL) && + operation_is_flag_set(op, OP_FLAG_BULK_IMPORT)) { + /* parentid is treated specially that is needed for the bulk import. (See #48755) */ + operator = SLAPI_OP_RANGE_NO_IDL_SORT|SLAPI_OP_RANGE_NO_ALLIDS; + } if (low == NULL) { - idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, - SLAPI_OP_LESS_OR_EQUAL, + operator |= SLAPI_OP_LESS_OR_EQUAL; + idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, operator, high, NULL, 0, &txn, err, allidslimit); } else if (high == NULL) { - idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, - SLAPI_OP_GREATER_OR_EQUAL, + operator |= SLAPI_OP_GREATER_OR_EQUAL; + idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, operator, low, NULL, 0, &txn, err, allidslimit); } else { - idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, - SLAPI_OP_LESS_OR_EQUAL, + operator |= SLAPI_OP_LESS_OR_EQUAL; + idl = index_range_read_ext(pb, be, type, (char*)indextype_EQUALITY, operator, low, high, 1, &txn, err, allidslimit); } diff --git a/ldap/servers/slapd/back-ldbm/idl_new.c b/ldap/servers/slapd/back-ldbm/idl_new.c index 25b3bfa2b..63df49f53 100644 --- a/ldap/servers/slapd/back-ldbm/idl_new.c +++ b/ldap/servers/slapd/back-ldbm/idl_new.c @@ -350,17 +350,31 @@ error: return idl; } +typedef struct _range_id_pair { + ID key; + ID id; +} idl_range_id_pair; /* * Perform the range search in the idl layer instead of the index layer * to improve the performance. */ +/* + * NOTE: + * In the total update (bulk import), an entry requires its ancestors already added. + * To guarantee it, the range search with parentid is used with setting the flag + * SLAPI_OP_RANGE_NO_IDL_SORT in operator. + * + * If the flag is set, + * 1. the IDList is not sorted by the ID. + * 2. holding to add an ID to the IDList unless the key is found in the IDList. + */ IDList * idl_new_range_fetch( - backend *be, - DB* db, - DBT *lowerkey, + backend *be, + DB* db, + DBT *lowerkey, DBT *upperkey, - DB_TXN *txn, + DB_TXN *txn, struct attrinfo *ai, int *flag_err, int allidslimit, @@ -380,7 +394,7 @@ idl_new_range_fetch( size_t count = 0; #ifdef DB_USE_BULK_FETCH /* beware that a large buffer on the stack might cause a stack overflow on some platforms */ - char buffer[BULK_FETCH_BUFFER_SIZE]; + char buffer[BULK_FETCH_BUFFER_SIZE]; void *ptr; DBT dataret; #endif @@ -388,15 +402,21 @@ idl_new_range_fetch( struct ldbminfo *li = (struct ldbminfo *)be->be_database->plg_private; time_t curtime; void *saved_key = NULL; + int coreop = operator & SLAPI_OP_RANGE; + ID key; + ID suffix; + idl_range_id_pair *leftover = NULL; + size_t leftoverlen = 32; + int leftovercnt = 0; if (NULL == flag_err) { return NULL; } - *flag_err = 0; if (NEW_IDL_NOOP == *flag_err) { return NULL; } + dblayer_txn_init(li, &s_txn); if (txn) { dblayer_read_txn_begin(be, txn, &s_txn); @@ -460,7 +480,7 @@ idl_new_range_fetch( #ifdef DB_USE_BULK_FETCH while (cur_key.data && (upperkey && upperkey->data ? - ((operator == SLAPI_OP_LESS) ? + ((coreop == SLAPI_OP_LESS) ? DBTcmp(&cur_key, upperkey, ai->ai_key_cmp_fn) < 0 : DBTcmp(&cur_key, upperkey, ai->ai_key_cmp_fn) <= 0) : PR_TRUE /* e.g., (x > a) */)) { @@ -496,6 +516,9 @@ idl_new_range_fetch( goto error; } } + if (operator & SLAPI_OP_RANGE_NO_IDL_SORT) { + key = (ID)strtol((char *)cur_key.data+1 , (char **)NULL, 10); + } while (PR_TRUE) { DB_MULTIPLE_NEXT(ptr, &data, dataret.data, dataret.size); if (dataret.data == NULL) break; @@ -524,7 +547,29 @@ idl_new_range_fetch( /* note the last id read to check for dups */ lastid = id; /* we got another ID, add it to our IDL */ - idl_rc = idl_append_extend(&idl, id); + if (operator & SLAPI_OP_RANGE_NO_IDL_SORT) { + if (!idl) { + /* First time. Keep the suffix ID. */ + suffix = key; + idl_rc = idl_append_extend(&idl, id); + } else if ((key == suffix) || idl_id_is_in_idlist(idl, key)) { + /* the parent is the suffix or already in idl. */ + idl_rc = idl_append_extend(&idl, id); + } else { + /* Otherwise, keep the {key,id} in leftover array */ + if (!leftover) { + leftover = (idl_range_id_pair *)slapi_ch_calloc(leftoverlen, sizeof(idl_range_id_pair)); + } else if (leftovercnt == leftoverlen) { + leftover = (idl_range_id_pair *)slapi_ch_realloc((char *)leftover, 2 * leftoverlen * sizeof(idl_range_id_pair)); + memset(leftover + leftovercnt, 0, leftoverlen); + leftoverlen *= 2; + } + leftover[leftovercnt].key = key; + leftover[leftovercnt++].id = id; + } + } else { + idl_rc = idl_append_extend(&idl, id); + } if (idl_rc) { LDAPDebug1Arg(LDAP_DEBUG_ANY, "unable to extend id list (err=%d)\n", idl_rc); @@ -581,7 +626,7 @@ idl_new_range_fetch( } #else while (upperkey && upperkey->data ? - ((operator == SLAPI_OP_LESS) ? + ((coreop == SLAPI_OP_LESS) ? DBTcmp(&cur_key, upperkey, ai->ai_key_cmp_fn) < 0 : DBTcmp(&cur_key, upperkey, ai->ai_key_cmp_fn) <= 0) : PR_TRUE /* e.g., (x > a) */) { @@ -698,9 +743,27 @@ error: *flag_err = ret; /* sort idl */ - if (idl && !ALLIDS(idl)) { - qsort((void *)&idl->b_ids[0], idl->b_nids, - (size_t)sizeof(ID), idl_sort_cmp); + if (idl && !ALLIDS(idl) && !(operator & SLAPI_OP_RANGE_NO_IDL_SORT)) { + qsort((void *)&idl->b_ids[0], idl->b_nids, (size_t)sizeof(ID), idl_sort_cmp); + } + if (operator & SLAPI_OP_RANGE_NO_IDL_SORT) { + int i; + int left = leftovercnt; + while (left) { + for (i = 0; i < leftovercnt; i++) { + if (leftover[i].key && idl_id_is_in_idlist(idl, leftover[i].key)) { + idl_rc = idl_append_extend(&idl, leftover[i].id); + if (idl_rc) { + LDAPDebug1Arg(LDAP_DEBUG_ANY, "unable to extend id list (err=%d)\n", idl_rc); + idl_free(&idl); + return NULL; + } + leftover[i].key = 0; + left--; + } + } + } + slapi_ch_free((void **)&leftover); } return idl; } diff --git a/ldap/servers/slapd/back-ldbm/index.c b/ldap/servers/slapd/back-ldbm/index.c index 00e78a7bc..81d662196 100644 --- a/ldap/servers/slapd/back-ldbm/index.c +++ b/ldap/servers/slapd/back-ldbm/index.c @@ -1232,6 +1232,7 @@ index_range_read_ext( int timelimit = -1; back_search_result_set *sr = NULL; int isroot = 0; + int coreop = operator & SLAPI_OP_RANGE; if (!pb) { LDAPDebug(LDAP_DEBUG_ANY, "index_range_read: NULL pblock\n", @@ -1278,7 +1279,7 @@ index_range_read_ext( LDAPDebug1Arg(LDAP_DEBUG_TRACE, "index_range_read lookthrough_limit=%d\n", lookthrough_limit); - switch( operator ) { + switch( coreop ) { case SLAPI_OP_LESS: case SLAPI_OP_LESS_OR_EQUAL: case SLAPI_OP_GREATER_OR_EQUAL: @@ -1287,7 +1288,7 @@ index_range_read_ext( default: LDAPDebug( LDAP_DEBUG_ANY, "<= index_range_read(%s,%s) NULL (operator %i)\n", - type, prefix, operator ); + type, prefix, coreop ); index_free_prefix(prefix); return( NULL ); } @@ -1343,7 +1344,7 @@ index_range_read_ext( if (range != 1) { /* open range search */ char *tmpbuf = NULL; /* this is a search with only one boundary value */ - switch( operator ) { + switch( coreop ) { case SLAPI_OP_LESS: case SLAPI_OP_LESS_OR_EQUAL: lowerkey.dptr = slapi_ch_strdup(prefix); @@ -1451,8 +1452,17 @@ index_range_read_ext( cur_key.data = lowerkey.data; cur_key.size = lowerkey.size; lowerkey.data = NULL; /* Don't need this any more, since the memory will be freed from cur_key */ - if (operator == SLAPI_OP_GREATER) { - *err = index_range_next_key(db,&cur_key,db_txn); + *err = 0; + if (coreop == SLAPI_OP_GREATER) { + *err = index_range_next_key(db, &cur_key, db_txn); + if (*err) { + LDAPDebug(LDAP_DEBUG_ANY, "<= index_range_read(%s,%s) op==GREATER, no next key: %i)\n", + type, prefix, *err ); + goto error; + } + } + if (operator & SLAPI_OP_RANGE_NO_ALLIDS) { + *err = NEW_IDL_NO_ALLID; } if (idl_get_idl_new()) { /* new idl */ idl = idl_new_range_fetch(be, db, &cur_key, &upperkey, db_txn, @@ -1462,7 +1472,7 @@ index_range_read_ext( int retry_count = 0; while (*err == 0 && (upperkey.data && - (operator == SLAPI_OP_LESS) ? + (coreop == SLAPI_OP_LESS) ? DBTcmp(&cur_key, &upperkey, ai->ai_key_cmp_fn) < 0 : DBTcmp(&cur_key, &upperkey, ai->ai_key_cmp_fn) <= 0)) { /* exit the loop when we either run off the end of the table, diff --git a/ldap/servers/slapd/back-ldbm/init.c b/ldap/servers/slapd/back-ldbm/init.c index a531abbf8..04cc9368f 100644 --- a/ldap/servers/slapd/back-ldbm/init.c +++ b/ldap/servers/slapd/back-ldbm/init.c @@ -36,7 +36,7 @@ ldbm_back_add_schema( Slapi_PBlock *pb ) SLAPI_ATTR_FLAG_NOUSERMOD ); rc |= slapi_add_internal_attr_syntax( LDBM_PARENTID_STR, - LDBM_PARENTID_OID, DIRSTRING_SYNTAX_OID, CASEIGNOREMATCH_NAME, + LDBM_PARENTID_OID, INTEGER_SYNTAX_OID, INTEGERMATCH_NAME, SLAPI_ATTR_FLAG_SINGLE|SLAPI_ATTR_FLAG_NOUSERMOD ); rc |= slapi_add_internal_attr_syntax( "entryid", diff --git a/ldap/servers/slapd/back-ldbm/ldbm_search.c b/ldap/servers/slapd/back-ldbm/ldbm_search.c index 8ed6b4d38..535529c4f 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_search.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_search.c @@ -1200,6 +1200,8 @@ subtree_candidates( int isroot = 0; struct ldbminfo *li = (struct ldbminfo *) be->be_database->plg_private; int allidslimit = compute_allids_limit(pb, li); + Operation *op = NULL; + PRBool is_bulk_import = PR_FALSE; /* make (|(originalfilter)(objectclass=referral)) */ ftop= create_subtree_filter(filter, managedsait, &focref, &forr); @@ -1216,6 +1218,12 @@ subtree_candidates( has_tombstone_filter = (filter->f_flags & SLAPI_FILTER_TOMBSTONE); slapi_pblock_get( pb, SLAPI_REQUESTOR_ISROOT, &isroot ); + /* Check if it is for bulk import. */ + slapi_pblock_get(pb, SLAPI_OPERATION, &op); + if (entryrdn_get_switch() && operation_is_flag_set(op, OP_FLAG_INTERNAL) && + operation_is_flag_set(op, OP_FLAG_BULK_IMPORT)) { + is_bulk_import = PR_TRUE; + } /* * Apply the DN components if the candidate list is greater than @@ -1237,13 +1245,13 @@ subtree_candidates( candidates = idl_intersection(be, candidates, descendants); idl_free(&tmp); idl_free(&descendants); - } else if (!has_tombstone_filter) { + } else if (!has_tombstone_filter && !is_bulk_import) { *err = ldbm_ancestorid_read_ext(be, &txn, e->ep_id, &descendants, allidslimit); idl_insert(&descendants, e->ep_id); candidates = idl_intersection(be, candidates, descendants); idl_free(&tmp); idl_free(&descendants); - } /* else == has_tombstone_filter: do nothing */ + } /* else == has_tombstone_filter OR is_bulk_import: do nothing */ } return( candidates ); @@ -1683,13 +1691,17 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) * >0 an ldap error code */ int filter_test = -1; + int is_bulk_import = operation_is_flag_set(op, OP_FLAG_BULK_IMPORT); - if((slapi_entry_flag_is_set(e->ep_entry,SLAPI_ENTRY_LDAPSUBENTRY) - && !filter_flag_is_set(filter,SLAPI_FILTER_LDAPSUBENTRY)) || - (slapi_entry_flag_is_set(e->ep_entry,SLAPI_ENTRY_FLAG_TOMBSTONE) - && ((!isroot && !filter_flag_is_set(filter, SLAPI_FILTER_RUV)) || - !filter_flag_is_set(filter, SLAPI_FILTER_TOMBSTONE)))) - { + if (is_bulk_import) { + /* If it is from bulk import, no need to check. */ + filter_test = 0; + slimit = -1; /* no sizelimit applied */ + } else if ((slapi_entry_flag_is_set(e->ep_entry,SLAPI_ENTRY_LDAPSUBENTRY) && + !filter_flag_is_set(filter,SLAPI_FILTER_LDAPSUBENTRY)) || + (slapi_entry_flag_is_set(e->ep_entry,SLAPI_ENTRY_FLAG_TOMBSTONE) && + ((!isroot && !filter_flag_is_set(filter, SLAPI_FILTER_RUV)) || + !filter_flag_is_set(filter, SLAPI_FILTER_TOMBSTONE)))) { /* If the entry is an LDAP subentry and filter don't filter subentries OR * the entry is a TombStone and filter don't filter Tombstone * don't return the entry. We make a special case to allow a non-root user @@ -1736,7 +1748,8 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) /* ugaston - if filter failed due to subentries or tombstones (filter_test=-1), * just forget about it, since we don't want to return anything at all. */ { - if ( slapi_uniqueIDCompareString(target_uniqueid, e->ep_entry->e_uniqueid) || + if ( is_bulk_import || + slapi_uniqueIDCompareString(target_uniqueid, e->ep_entry->e_uniqueid) || slapi_sdn_scope_test_ext( backentry_get_sdn(e), basesdn, scope, e->ep_entry->e_flags )) { /* check size limit */ @@ -1781,7 +1794,7 @@ ldbm_back_next_search_entry_ext( Slapi_PBlock *pb, int use_extension ) } rc = 0; goto bail; - } + } else { CACHE_RETURN ( &inst->inst_cache, &(sr->sr_entry) ); diff --git a/ldap/servers/slapd/back-ldbm/misc.c b/ldap/servers/slapd/back-ldbm/misc.c index fe3d01bfb..77c1e70fe 100644 --- a/ldap/servers/slapd/back-ldbm/misc.c +++ b/ldap/servers/slapd/back-ldbm/misc.c @@ -79,6 +79,7 @@ static const char *systemIndexes[] = { SLAPI_ATTR_NSCP_ENTRYDN, ATTR_NSDS5_REPLCONFLICT, SLAPI_ATTR_ENTRYUSN, + SLAPI_ATTR_PARENTID, NULL }; diff --git a/ldap/servers/slapd/entry.c b/ldap/servers/slapd/entry.c index 3124ff6af..d38f9709b 100644 --- a/ldap/servers/slapd/entry.c +++ b/ldap/servers/slapd/entry.c @@ -3429,8 +3429,8 @@ slapi_entry_rename(Slapi_Entry *e, const char *newrdn, int deleteoldrdn, Slapi_D /* We remove the parentid and entrydn since the backend will change these. * We don't want to give the caller an inconsistent entry. */ - slapi_entry_attr_delete(e, "parentid"); - slapi_entry_attr_delete(e, "entrydn"); + slapi_entry_attr_delete(e, SLAPI_ATTR_PARENTID); + slapi_entry_attr_delete(e, SLAPI_ATTR_ENTRYDN); /* Build new DN. If newsuperior is set, just use "newrdn,newsuperior". If * newsuperior is not set, need to add newrdn to old superior. */ diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index 645cdd519..b74f9bdfa 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -536,12 +536,16 @@ typedef int (*SyntaxEnumFunc)(char **names, Slapi_PluginDesc *plugindesc, /* OIDs for some commonly used matching rules */ #define DNMATCH_OID "2.5.13.1" /* distinguishedNameMatch */ #define CASEIGNOREMATCH_OID "2.5.13.2" /* caseIgnoreMatch */ +#define INTEGERMATCH_OID "2.5.13.14" /* integerMatch */ +#define INTEGERORDERINGMATCH_OID "2.5.13.15" /* integerOrderingMatch */ #define INTFIRSTCOMPMATCH_OID "2.5.13.29" /* integerFirstComponentMatch */ #define OIDFIRSTCOMPMATCH_OID "2.5.13.30" /* objectIdentifierFirstComponentMatch */ /* Names for some commonly used matching rules */ #define DNMATCH_NAME "distinguishedNameMatch" #define CASEIGNOREMATCH_NAME "caseIgnoreMatch" +#define INTEGERMATCH_NAME "integerMatch" +#define INTEGERORDERINGMATCH_NAME "integerOrderingMatch" #define INTFIRSTCOMPMATCH_NAME "integerFirstComponentMatch" #define OIDFIRSTCOMPMATCH_NAME "objectIdentifierFirstComponentMatch" diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index d3a6b25b8..a7e544ad3 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -483,6 +483,7 @@ NSPR_API(PRUint32) PR_fprintf(struct PRFileDesc* fd, const char *fmt, ...) #define SLAPI_ATTR_ENTRYDN "entrydn" #define SLAPI_ATTR_DN "dn" #define SLAPI_ATTR_RDN "rdn" +#define SLAPI_ATTR_PARENTID "parentid" #define SLAPI_ATTR_UNIQUEID_LENGTH 10 #define SLAPI_ATTR_OBJECTCLASS_LENGTH 11 #define SLAPI_ATTR_VALUE_TOMBSTONE_LENGTH 11 @@ -494,6 +495,7 @@ NSPR_API(PRUint32) PR_fprintf(struct PRFileDesc* fd, const char *fmt, ...) #define SLAPI_ATTR_ENTRYDN_LENGTH 7 #define SLAPI_ATTR_DN_LENGTH 2 #define SLAPI_ATTR_RDN_LENGTH 3 +#define SLAPI_ATTR_PARENTID_LENGTH 8 /* plugin shared config area */ #define SLAPI_PLUGIN_SHARED_CONFIG_AREA "nsslapd-pluginConfigArea" @@ -7024,6 +7026,9 @@ typedef struct slapi_plugindesc { #define SLAPI_OP_GREATER_OR_EQUAL 4 #define SLAPI_OP_GREATER 5 #define SLAPI_OP_SUBSTRING 6 +#define SLAPI_OP_RANGE 0xff +#define SLAPI_OP_RANGE_NO_IDL_SORT 0x100 +#define SLAPI_OP_RANGE_NO_ALLIDS 0x200 /* Defined values of SLAPI_PLUGIN_MR_USAGE: */ #define SLAPI_PLUGIN_MR_USAGE_INDEX 0 @@ -7607,7 +7612,8 @@ enum BACK_INFO_CRYPT_ENCRYPT_VALUE, /* Ctrl: clcrypt_encrypt_value */ BACK_INFO_CRYPT_DECRYPT_VALUE, /* Ctrl: clcrypt_decrypt_value */ BACK_INFO_DIRECTORY, /* Get the directory path */ - BACK_INFO_LOG_DIRECTORY /* Get the txn log directory */ + BACK_INFO_LOG_DIRECTORY, /* Get the txn log directory */ + BACK_INFO_IS_ENTRYRDN /* Get the flag for entryrdn */ }; struct _back_info_crypt_init { diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 76365592a..52d1c4a1b 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -416,6 +416,7 @@ char *slapi_filter_to_string_internal( const struct slapi_filter *f, char *buf, #define OP_FLAG_REVERSE_CANDIDATE_ORDER 0x100000 /* reverse the search candidate list */ #define OP_FLAG_NEVER_CACHE 0x200000 /* never keep the entry in cache */ #define OP_FLAG_TOMBSTONE_FIXUP 0x400000 /* operation is tombstone fixup op */ +#define OP_FLAG_BULK_IMPORT 0x800000 /* operation is bulk import */ /* reverse search states */ #define REV_STARTED 1
0
6c9822577b32af674dae2f884030bf2fd8a51bc2
389ds/389-ds-base
Bug 690584 - #10641 reslimit_bv2int - fix coverity resource leak issues https://bugzilla.redhat.com/show_bug.cgi?id=690584 Resolves: bug 690584 Bug Description: #10641 reslimit_bv2int - fix coverity resource leak issues Reviewed by: nhosoi (Thanks!) Branch: master Fix Description: The comment was incorrect - slapi_value_get_int does handle signed values correctly - it uses the same function atoi - the fix is to get rid of reslimit_bv2int Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no
commit 6c9822577b32af674dae2f884030bf2fd8a51bc2 Author: Rich Megginson <[email protected]> Date: Fri Mar 25 10:48:27 2011 -0600 Bug 690584 - #10641 reslimit_bv2int - fix coverity resource leak issues https://bugzilla.redhat.com/show_bug.cgi?id=690584 Resolves: bug 690584 Bug Description: #10641 reslimit_bv2int - fix coverity resource leak issues Reviewed by: nhosoi (Thanks!) Branch: master Fix Description: The comment was incorrect - slapi_value_get_int does handle signed values correctly - it uses the same function atoi - the fix is to get rid of reslimit_bv2int Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/resourcelimit.c b/ldap/servers/slapd/resourcelimit.c index dc22a0a07..563381f2d 100644 --- a/ldap/servers/slapd/resourcelimit.c +++ b/ldap/servers/slapd/resourcelimit.c @@ -181,7 +181,6 @@ static void reslimit_connext_destructor( void *extension, void *object, void *parent ); static int reslimit_get_ext( Slapi_Connection *conn, const char *logname, SLAPIResLimitConnData **rlcdpp ); -static int reslimit_bv2int( const struct berval *bvp ); static char ** reslimit_get_registered_attributes(); @@ -327,38 +326,6 @@ reslimit_get_ext( Slapi_Connection *conn, const char *logname, } -/* - * utility function to convert a string-represented integer to an int. - * - * XXXmcs: wouldn't need this if slapi_value_get_int() returned a signed int! - */ -static int -reslimit_bv2int( const struct berval *bvp ) -{ - int rc = 0; - char smallbuf[ 25 ], *buf; - - if ( bvp != NULL ) { - /* make a copy to ensure it is zero-terminated */ - if ( bvp->bv_len < sizeof( smallbuf )) { - buf = smallbuf; - } else { - buf = slapi_ch_malloc( bvp->bv_len + 1 ); - } - memcpy( buf, bvp->bv_val, bvp->bv_len); - buf[ bvp->bv_len ] = '\0'; - - rc = atoi( buf ); - - if ( buf != smallbuf ) { - slapi_ch_free( (void **)&smallbuf ); - } - } - - return( rc ); -} - - /**** Semi-public functions start here ***********************************/ /* * These functions are exposed to other parts of the server only, i.e., @@ -464,11 +431,10 @@ reslimit_update_from_entry( Slapi_Connection *conn, Slapi_Entry *e ) &actual_type_name, 0, &free_flags )) { Slapi_Value *v; int index; - const struct berval *bvp; - if (( index = slapi_valueset_first_value( vs, &v )) != -1 && - ( bvp = slapi_value_get_berval( v )) != NULL ) { - rlcdp->rlcd_integer_value[ i ] = reslimit_bv2int( bvp ); + if ((( index = slapi_valueset_first_value( vs, &v )) != -1) && + ( v != NULL )) { + rlcdp->rlcd_integer_value[ i ] = slapi_value_get_int( v ); rlcdp->rlcd_integer_available[ i ] = PR_TRUE; LDAPDebug( SLAPI_RESLIMIT_TRACELEVEL,
0
a5b1558384e445f95201987d0125c4706af97e11
389ds/389-ds-base
Issue 5648 - Covscan - Compiler warnings (#5651) Description: A covscan report on 389-ds-base=-2.2.4 reported two compiler warnings. Defect type: COMPILER_WARNING 389-ds-base-2.2.4/ldap/servers/plugins/retrocl/retrocl_trim.c:458:27: warning[-Wmaybe-uninitialized]: 'trim_interval' may be used uninitialized in this function Defect type: COMPILER_WARNING 389-ds-base-2.2.4/ldap/servers/plugins/retrocl/retrocl_trim.c:26:40: warning[-Wint-conversion]: initialization of 'int' from 'void *' makes integer from pointer without a cast One has since been fixed, this is for the remaining one. relates: https://github.com/389ds/389-ds-base/issues/5648 Reviewed by: @mreynolds389 (Thanks)
commit a5b1558384e445f95201987d0125c4706af97e11 Author: James Chapman <[email protected]> Date: Mon Feb 13 11:55:23 2023 +0000 Issue 5648 - Covscan - Compiler warnings (#5651) Description: A covscan report on 389-ds-base=-2.2.4 reported two compiler warnings. Defect type: COMPILER_WARNING 389-ds-base-2.2.4/ldap/servers/plugins/retrocl/retrocl_trim.c:458:27: warning[-Wmaybe-uninitialized]: 'trim_interval' may be used uninitialized in this function Defect type: COMPILER_WARNING 389-ds-base-2.2.4/ldap/servers/plugins/retrocl/retrocl_trim.c:26:40: warning[-Wint-conversion]: initialization of 'int' from 'void *' makes integer from pointer without a cast One has since been fixed, this is for the remaining one. relates: https://github.com/389ds/389-ds-base/issues/5648 Reviewed by: @mreynolds389 (Thanks) diff --git a/ldap/servers/plugins/retrocl/retrocl_trim.c b/ldap/servers/plugins/retrocl/retrocl_trim.c index d6b24c8bf..158f801cc 100644 --- a/ldap/servers/plugins/retrocl/retrocl_trim.c +++ b/ldap/servers/plugins/retrocl/retrocl_trim.c @@ -423,7 +423,7 @@ retrocl_init_trimming(void) const char *cl_maxage; time_t ageval = 0; /* Don't trim, by default */ const char *cl_trim_interval; - int trim_interval; + int trim_interval = DEFAULT_CHANGELOGDB_TRIM_INTERVAL; cl_maxage = retrocl_get_config_str(CONFIG_CHANGELOG_MAXAGE_ATTRIBUTE); if (cl_maxage) {
0
0e4b06145c842c3b2c77a20f83142ed2cf3f87e2
389ds/389-ds-base
bump version to 1.3.5.3
commit 0e4b06145c842c3b2c77a20f83142ed2cf3f87e2 Author: Noriko Hosoi <[email protected]> Date: Sat May 7 15:55:12 2016 -0700 bump version to 1.3.5.3 diff --git a/VERSION.sh b/VERSION.sh index 0cede259f..75bac70f4 100644 --- a/VERSION.sh +++ b/VERSION.sh @@ -10,7 +10,7 @@ vendor="389 Project" # PACKAGE_VERSION is constructed from these VERSION_MAJOR=1 VERSION_MINOR=3 -VERSION_MAINT=5.2 +VERSION_MAINT=5.3 # NOTE: VERSION_PREREL is automatically set for builds made out of a git tree VERSION_PREREL= VERSION_DATE=`date -u +%Y%m%d%H%M%S`
0
355d7076b054d50b8227c22263cd5a8cb214d4f0
389ds/389-ds-base
Ticket 49006 - Enable nunc-stans by default. Fix Description: This change will enable nunc-stans by default in all 1.3.6 builds of directory server. https://fedorahosted.org/389/ticket/49006 Author: wibrown Review by: nhosoi (Thanks!)
commit 355d7076b054d50b8227c22263cd5a8cb214d4f0 Author: William Brown <[email protected]> Date: Wed Oct 12 13:52:03 2016 +1000 Ticket 49006 - Enable nunc-stans by default. Fix Description: This change will enable nunc-stans by default in all 1.3.6 builds of directory server. https://fedorahosted.org/389/ticket/49006 Author: wibrown Review by: nhosoi (Thanks!) diff --git a/ldap/servers/slapd/libglobs.c b/ldap/servers/slapd/libglobs.c index df0c0b961..2e0795048 100644 --- a/ldap/servers/slapd/libglobs.c +++ b/ldap/servers/slapd/libglobs.c @@ -1668,7 +1668,7 @@ FrontendConfig_init(void) { cfg->maxsimplepaged_per_conn = DEFAULT_MAXSIMPLEPAGED_PER_CONN; cfg->maxbersize = DEFAULT_MAXBERSIZE; #ifdef ENABLE_NUNC_STANS - init_enable_nunc_stans = cfg->enable_nunc_stans = LDAP_OFF; + init_enable_nunc_stans = cfg->enable_nunc_stans = LDAP_ON; #endif #if defined(LINUX) init_malloc_mxfast = cfg->malloc_mxfast = DEFAULT_MALLOC_UNSET;
0
4fae1bc846878534f847aa783505ee960eab261a
389ds/389-ds-base
Pull DS Console as a component
commit 4fae1bc846878534f847aa783505ee960eab261a Author: Nathan Kinder <[email protected]> Date: Tue Mar 15 00:48:04 2005 +0000 Pull DS Console as a component diff --git a/Makefile b/Makefile index 7e4ecdca8..4c7d2cb1a 100644 --- a/Makefile +++ b/Makefile @@ -90,7 +90,7 @@ components: $(ADMINUTIL_DEP) $(NSPR_DEP) $(ARLIB_DEP) $(DBM_DEP) $(SECURITY_DEP) -@echo "The components are up to date" ifeq ($(BUILD_JAVA_CODE),1) -DS_CONSOLE_COMPONENT_DEP = $(LDAPJDK_DEP) $(SWING_DEP) $(MCC_DEP) +DS_CONSOLE_COMPONENT_DEP = $(LDAPJDK_DEP) $(SWING_DEP) $(MCC_DEP) $(LDAPCONSOLE_DEP) DS_CONSOLE_COMPONENT_DEP += $(JAVASSL_DEP) $(JSS_DEP) $(CRIMSONJAR_DEP) java_platform_check: @@ -201,7 +201,7 @@ cleanDirectory: buildDirectoryConsole: consoleComponents java_platform_check ifeq ($(BUILD_JAVA_CODE),1) - cd ldap/admin/src/java/com/netscape/admin/dirserv; $(MAKE) $(MFLAGS) package +# cd ldap/admin/src/java/com/netscape/admin/dirserv; $(MAKE) $(MFLAGS) package cd ldap/admin/src/java/com/netscape/xmltools; $(MAKE) $(MFLAGS) package endif diff --git a/component_versions.mk b/component_versions.mk index 5e62c1a97..b4cb45826 100644 --- a/component_versions.mk +++ b/component_versions.mk @@ -142,6 +142,17 @@ ifndef MCC_RELDATE MCC_RELDATE=20041117 endif +# LDAP Console +ifndef LDAPCONSOLE_REL + LDAPCONSOLE_REL=71 +endif +ifndef LDAPCONSOLE_COMP + LDAPCONSOLE_COMP = ldapconsole$(LDAPCONSOLE_REL) +endif +ifndef LDAPCONSOLE_RELDATE + LDAPCONSOLE_RELDATE=20050314 +endif + ifndef PERLDAP_VERSION PERLDAP_VERSION=20041116 endif diff --git a/components.mk b/components.mk index 9751df7a8..ac6e0d138 100644 --- a/components.mk +++ b/components.mk @@ -761,6 +761,29 @@ endif fi ########################################################### +# LDAP Console java classes +########################################################### +LDAPCONSOLEJAR = ds$(LDAPCONSOLE_REL).jar +LDAPCONSOLEJAR_EN = ds$(LDAPCONSOLE_REL)_en.jar + +LDAPCONSOLE_RELEASE=$(COMPONENTS_DIR_DEV) +LDAPCONSOLE_JARDIR = $(LDAPCONSOLE_RELEASE)/$(LDAPCONSOLE_COMP)ext/$(LDAPCONSOLE_RELDATE)/jars +LDAPCONSOLE_DEP = $(CLASS_DEST)/$(LDAPCONSOLEJAR) +LDAPCONSOLE_FILES=$(LDAPCONSOLEJAR),$(LDAPCONSOLEJAR_EN) + +ifndef LDAPCONSOLE_PULL_METHOD +LDAPCONSOLE_PULL_METHOD = $(COMPONENT_PULL_METHOD) +endif + +$(LDAPCONSOLE_DEP): $(CLASS_DEST) +ifdef COMPONENT_DEPS + $(FTP_PULL) -method $(LDAPCONSOLE_PULL_METHOD) \ + -objdir $(CLASS_DEST) -componentdir $(LDAPCONSOLE_JARDIR) \ + -files $(LDAPCONSOLE_FILES) +endif + -@if [ ! -f $@ ] ; \ + then echo "Error: could not get component LDAPCONSOLE file $@" ; \ + fi ########################################################### ### Perldap package ####################################### diff --git a/ldap/cm/Makefile b/ldap/cm/Makefile index 5e02a8bed..ba5e5cbba 100644 --- a/ldap/cm/Makefile +++ b/ldap/cm/Makefile @@ -203,8 +203,6 @@ NSDIST = $(BUILD_ROOT)/../dist DS_JAR_SRC_PATH = $(NSDIST)/$(BUILD_DEBUG) DS_JAR_DEST_PATH = java/jars -DS_JAR_FILE = ds71.jar -DS_JAR_LANG_FILE = ds71_en.jar XMLTOOLS_JAR_FILE = xmltools.jar UNZIP=unzip -o @@ -408,8 +406,8 @@ endif # install the ds jar file in the <server root>/$(DS_JAR_DEST_PATH) directory # also install the other jar files we use - $(INSTALL) -m 644 $(DS_JAR_SRC_PATH)/$(DS_JAR_FILE) $(RELDIR)/$(DS_JAR_DEST_PATH) - $(INSTALL) -m 644 $(DS_JAR_SRC_PATH)/$(DS_JAR_LANG_FILE) $(RELDIR)/$(DS_JAR_DEST_PATH) + $(INSTALL) -m 644 $(NSDIST)/classes/$(LDAPCONSOLEJAR) $(RELDIR)/$(DS_JAR_DEST_PATH) + $(INSTALL) -m 644 $(NSDIST)/classes/$(LDAPCONSOLEJAR_EN) $(RELDIR)/$(DS_JAR_DEST_PATH) $(INSTALL) -m 644 $(DS_JAR_SRC_PATH)/$(XMLTOOLS_JAR_FILE) $(RELDIR)/$(DS_JAR_DEST_PATH) $(INSTALL) -m 644 $(NSDIST)/classes/$(CRIMSONJAR) $(RELDIR)/$(DS_JAR_DEST_PATH) $(INSTALL) -m 644 $(NSDIST)/classes/$(CRIMSON_LICENSE) $(RELDIR)/$(DS_JAR_DEST_PATH)
0
bef946f15f1e7f5694e8e044df3444d78b558d4f
389ds/389-ds-base
Bug 630092 - Coverity #12117: Resource leaks issues https://bugzilla.redhat.com/show_bug.cgi?id=630092 Description: The putvalue() has been modified to release b64 using freeEnc64() before it returns.
commit bef946f15f1e7f5694e8e044df3444d78b558d4f Author: Endi Sukma Dewata <[email protected]> Date: Tue Sep 14 20:25:53 2010 -0400 Bug 630092 - Coverity #12117: Resource leaks issues https://bugzilla.redhat.com/show_bug.cgi?id=630092 Description: The putvalue() has been modified to release b64 using freeEnc64() before it returns. diff --git a/ldap/servers/slapd/tools/mmldif.c b/ldap/servers/slapd/tools/mmldif.c index b364a19ce..6d6233887 100644 --- a/ldap/servers/slapd/tools/mmldif.c +++ b/ldap/servers/slapd/tools/mmldif.c @@ -1245,7 +1245,7 @@ putvalue( int valuelen ) { - Enc64_t * b64; + Enc64_t * b64 = NULL; char * lptr; char line[255]; int return_code; @@ -1330,6 +1330,7 @@ putvalue( } return_bit: + if (b64) freeEnc64(b64); if (tag != NULL) { fputs("-\n", fh); }
0
61a3e9ef02b49a8a987b366188d9db05e5449aa0
389ds/389-ds-base
[189264] 6.11->6.21 upgrade, no db housekeeping threads The problem was check_db_version finds the existing DBVERSION is old and set dblayer_private->blayer_recovery_required = 1. If it's set, DBLAYER_CLEAN_RECOVER_MODE is processed properly. Unfortunately, it was "reinitialized" in the function read_metadata, which is called after check_db_version.
commit 61a3e9ef02b49a8a987b366188d9db05e5449aa0 Author: Noriko Hosoi <[email protected]> Date: Tue Apr 18 18:25:02 2006 +0000 [189264] 6.11->6.21 upgrade, no db housekeeping threads The problem was check_db_version finds the existing DBVERSION is old and set dblayer_private->blayer_recovery_required = 1. If it's set, DBLAYER_CLEAN_RECOVER_MODE is processed properly. Unfortunately, it was "reinitialized" in the function read_metadata, which is called after check_db_version. diff --git a/ldap/servers/slapd/back-ldbm/dblayer.c b/ldap/servers/slapd/back-ldbm/dblayer.c index 79be35b89..2168e5143 100644 --- a/ldap/servers/slapd/back-ldbm/dblayer.c +++ b/ldap/servers/slapd/back-ldbm/dblayer.c @@ -3830,6 +3830,10 @@ static int read_metadata(struct ldbminfo *li) int number = 0; dblayer_private *priv = (dblayer_private *)li->li_dblayer_private; + /* dblayer_recovery_required is initialized in dblayer_init; + * and might be set 1 in check_db_version; + * we don't want to override it + * priv->dblayer_recovery_required = 0; */ priv->dblayer_previous_cachesize = 0; priv->dblayer_previous_ncache = 0; /* Open the guard file and read stuff, then delete it */ @@ -3838,12 +3842,10 @@ static int read_metadata(struct ldbminfo *li) memset(&prfinfo, '\0', sizeof(PRFileInfo)); (void)PR_GetFileInfo(filename, &prfinfo); - priv->dblayer_recovery_required = 0; prfd = PR_Open(filename,PR_RDONLY,priv->dblayer_file_mode); if (NULL == prfd || 0 == prfinfo.size) { /* file empty or not present--means the database needs recovered */ int count = 0; - priv->dblayer_recovery_required = 0; for (dirp = priv->dblayer_data_directories; dirp && *dirp; dirp++) { count_dbfiles_in_dir(*dirp, &count, 1 /* recurse */); @@ -3877,10 +3879,6 @@ static int read_metadata(struct ldbminfo *li) } return 0; /* no files found; no need to run recover start */ } - /* dblayer_recovery_required is initialized in dblayer_init; - * and might be set 1 in check_db_version; - * we don't want to override it - * priv->dblayer_recovery_required = 0; */ /* So, we opened the file, now let's read the cache size and version stuff */ buf = slapi_ch_calloc(1, prfinfo.size + 1);
0
28a607a6bfed369b9f0c82e8b5ef4b50c158a928
389ds/389-ds-base
pass the string copy to slapi_dn_normalize_original slapi_dn_normalize_original can modify the argument string, so we cannot pass in a const char *rawdn to that function - instead, pass in a copy created by slapi_ch_strdup
commit 28a607a6bfed369b9f0c82e8b5ef4b50c158a928 Author: Rich Megginson <[email protected]> Date: Wed Sep 1 12:35:26 2010 -0600 pass the string copy to slapi_dn_normalize_original slapi_dn_normalize_original can modify the argument string, so we cannot pass in a const char *rawdn to that function - instead, pass in a copy created by slapi_ch_strdup diff --git a/ldap/servers/slapd/entry.c b/ldap/servers/slapd/entry.c index aa83c96fb..82fbbb2cd 100644 --- a/ldap/servers/slapd/entry.c +++ b/ldap/servers/slapd/entry.c @@ -264,7 +264,7 @@ str2entry_fast( const char *rawdn, char *s, int flags, int read_stateinfo ) if ( NULL == slapi_entry_get_dn_const( e )) { if (flags & SLAPI_STR2ENTRY_USE_OBSOLETE_DNFORMAT) { normdn = - slapi_ch_strdup(slapi_dn_normalize_original(rawdn)); + slapi_dn_normalize_original(slapi_ch_strdup(rawdn)); } else { normdn = slapi_create_dn_string("%s", rawdn); if (NULL == normdn) { @@ -286,7 +286,7 @@ str2entry_fast( const char *rawdn, char *s, int flags, int read_stateinfo ) } else { if (flags & SLAPI_STR2ENTRY_USE_OBSOLETE_DNFORMAT) { normdn = - slapi_ch_strdup(slapi_dn_normalize_original(rawdn)); + slapi_dn_normalize_original(slapi_ch_strdup(rawdn)); } else { normdn = slapi_create_dn_string("%s", rawdn); if (NULL == normdn) {
0
44ebe2287e8cee0c0c96e20c27621689428e6cbc
389ds/389-ds-base
Ticket #626 - Possible to add nonexistent target to ACI Fix description: This patch checks if the acl target exists and logs a warning in the server log if the target does not exist. It does not, however, validate targets containing wildcards or macros https://fedorahosted.org/389/ticket/626 Reviewed by rmeggins and nhosoi.
commit 44ebe2287e8cee0c0c96e20c27621689428e6cbc Author: Anupam Jain <[email protected]> Date: Thu Aug 1 15:13:32 2013 -0700 Ticket #626 - Possible to add nonexistent target to ACI Fix description: This patch checks if the acl target exists and logs a warning in the server log if the target does not exist. It does not, however, validate targets containing wildcards or macros https://fedorahosted.org/389/ticket/626 Reviewed by rmeggins and nhosoi. diff --git a/ldap/servers/plugins/acl/acl.c b/ldap/servers/plugins/acl/acl.c index a05037cfc..ce0fb9227 100644 --- a/ldap/servers/plugins/acl/acl.c +++ b/ldap/servers/plugins/acl/acl.c @@ -1494,16 +1494,16 @@ acl_check_mods( ** syntax */ if (strcmp(mod->mod_type, - aci_attr_type) == 0) { - if ( 0 != (rv = acl_verify_syntax( e_sdn, - mod->mod_bvalues[i], errbuf))) { + aci_attr_type) == 0) { + if ( 0 != (rv = acl_verify_syntax(pb, e_sdn, + mod->mod_bvalues[i], errbuf))) { aclutil_print_err(rv, e_sdn, mod->mod_bvalues[i], - errbuf); + errbuf); /* Cleanup */ slapi_mods_done(&smods); return LDAP_INVALID_SYNTAX; - } + } } } /* for */ } @@ -1680,8 +1680,8 @@ acl_modified (Slapi_PBlock *pb, int optype, Slapi_DN *e_sdn, void *change) acllist_acicache_WRITE_LOCK(); i= slapi_attr_first_value ( attr,&sval ); while ( i != -1 ) { - attrVal = slapi_value_get_berval(sval); - rv= acllist_insert_aci_needsLock(e_sdn, attrVal ); + attrVal = slapi_value_get_berval(sval); + rv= acllist_insert_aci_needsLock_ext(pb, e_sdn, attrVal ); if (rv <= ACL_ERR) aclutil_print_err(rv, e_sdn, attrVal, NULL); /* Print the aci list */ @@ -1722,10 +1722,10 @@ acl_modified (Slapi_PBlock *pb, int optype, Slapi_DN *e_sdn, void *change) if (bvalue == NULL) break; for (; *bvalue != NULL; ++bvalue) { - rv=acllist_insert_aci_needsLock( e_sdn, *bvalue); + rv=acllist_insert_aci_needsLock_ext(pb, e_sdn, *bvalue); if (rv <= ACL_ERR) { - aclutil_print_err(rv, e_sdn, - *bvalue, NULL); + aclutil_print_err(rv, e_sdn, + *bvalue, NULL); } } } else { @@ -1735,10 +1735,10 @@ acl_modified (Slapi_PBlock *pb, int optype, Slapi_DN *e_sdn, void *change) for (; *value != NULL; ++value) { b.bv_len = strlen (*value); b.bv_val = *value; - rv=acllist_insert_aci_needsLock( e_sdn, &b); + rv=acllist_insert_aci_needsLock_ext(pb, e_sdn, &b); if (rv <= ACL_ERR) { - aclutil_print_err(rv, e_sdn, - &b, NULL); + aclutil_print_err(rv, e_sdn, + &b, NULL); } } } diff --git a/ldap/servers/plugins/acl/acl.h b/ldap/servers/plugins/acl/acl.h index 13c6f9047..9e92252fa 100644 --- a/ldap/servers/plugins/acl/acl.h +++ b/ldap/servers/plugins/acl/acl.h @@ -808,14 +808,17 @@ int acl_access_allowed_main ( Slapi_PBlock *pb, Slapi_Entry *e, char **attrs, struct berval *val, int access , int flags, char **errbuf); int acl_access_allowed( Slapi_PBlock *pb, Slapi_Entry *e, char *attr, struct berval *val, int access ); -int acl_verify_syntax(const Slapi_DN *e_sdn, const struct berval *bval, char **errbuf); aclUserGroup * acl_get_usersGroup ( struct acl_pblock *aclpb , char *n_dn); void acl_print_acllib_err (NSErr_t *errp , char * str); int acl_check_mods( Slapi_PBlock *pb, Slapi_Entry *e, LDAPMod **mods, char **errbuf ); -int acl_verify_aci_syntax (Slapi_Entry *e, char **errbuf); char * acl__access2str(int access); void acl_strcpy_special (char *d, char *s); -int acl_parse(char *str, aci_t *aci_item, char **errbuf); +int acl_parse(Slapi_PBlock *pb, char * str, aci_t *aci_item, char **errbuf); +int acl_verify_aci_syntax (Slapi_PBlock *pb, Slapi_Entry *e, char **errbuf); +int acl_verify_syntax(Slapi_PBlock *pb, const Slapi_DN *e_sdn, + const struct berval *bval, char **errbuf); +int acllist_insert_aci_needsLock_ext( Slapi_PBlock *pb, const Slapi_DN *e_sdn, + const struct berval* aci_attr); char * acl_access2str ( int access ); int acl_init_ext (); void * acl_get_ext (ext_type type, void *object); @@ -864,7 +867,7 @@ void acllist_acicache_WRITE_UNLOCK(void); void acllist_acicache_WRITE_LOCK(void); void acllist_aciscan_update_scan ( Acl_PBlock *aclpb, char *edn ); int acllist_remove_aci_needsLock( const Slapi_DN *sdn, const struct berval *attr ); -int acllist_insert_aci_needsLock( const Slapi_DN *e_sdn, const struct berval* aci_attr); +int acllist_insert_aci_needsLock( const Slapi_DN *e_sdn, const struct berval* aci_attr); int acllist_init (); int acllist_moddn_aci_needsLock ( Slapi_DN *oldsdn, char *newdn ); void acllist_print_tree ( Avlnode *root, int *depth, char *start, char *side); diff --git a/ldap/servers/plugins/acl/acllist.c b/ldap/servers/plugins/acl/acllist.c index 623a739a4..c01bed38c 100644 --- a/ldap/servers/plugins/acl/acllist.c +++ b/ldap/servers/plugins/acl/acllist.c @@ -97,7 +97,6 @@ static void __acllist_free_aciContainer ( AciContainer **container); void my_print( Avlnode *root ); - int acllist_init () { @@ -195,6 +194,12 @@ void acl_be_state_change_fnc ( void *handle, char *be_name, int old_state, /* This routine must be called with the acicache write lock taken */ int acllist_insert_aci_needsLock( const Slapi_DN *e_sdn, const struct berval* aci_attr) +{ + return(acllist_insert_aci_needsLock_ext(NULL, e_sdn, aci_attr)); +} + +int +acllist_insert_aci_needsLock_ext( Slapi_PBlock *pb, const Slapi_DN *e_sdn, const struct berval* aci_attr) { aci_t *aci; @@ -209,7 +214,7 @@ acllist_insert_aci_needsLock( const Slapi_DN *e_sdn, const struct berval* aci_at acl_str = slapi_ch_strdup(aci_attr->bv_val); /* Parse the ACL TEXT */ - if ( 0 != (rv = acl_parse ( acl_str, aci, NULL )) ) { + if ( 0 != (rv = acl_parse ( pb, acl_str, aci, NULL )) ) { slapi_log_error (SLAPI_LOG_FATAL, plugin_name, "ACL PARSE ERR(rv=%d): %s\n", rv, acl_str ); slapi_ch_free ( (void **) &acl_str ); diff --git a/ldap/servers/plugins/acl/aclparse.c b/ldap/servers/plugins/acl/aclparse.c index a8a38a176..ce44964cc 100644 --- a/ldap/servers/plugins/acl/aclparse.c +++ b/ldap/servers/plugins/acl/aclparse.c @@ -65,7 +65,6 @@ static int acl_verify_exactly_one_attribute( char *attr_name, Slapi_Filter *f); static int type_compare( Slapi_Filter *f, void *arg); static int acl_check_for_target_macro( aci_t *aci_item, char *value); static int get_acl_rights_as_int( char * strValue); - /*************************************************************************** * * acl_parse @@ -75,6 +74,7 @@ static int get_acl_rights_as_int( char * strValue); * * * Input: +* Slapi_PBlock *pb - Parameter block * char *str - Input string which has the ACL * This is a duped copy, so here we have * the right to stich '\0' characters into str for @@ -93,7 +93,7 @@ static int get_acl_rights_as_int( char * strValue); * **************************************************************************/ int -acl_parse(char * str, aci_t *aci_item, char **errbuf) +acl_parse(Slapi_PBlock *pb, char * str, aci_t *aci_item, char **errbuf) { int rv=0; @@ -110,10 +110,10 @@ acl_parse(char * str, aci_t *aci_item, char **errbuf) } } else if (!next) { /* the statement does not start with a parenthesis */ - return(ACL_SYNTAX_ERR); - } else { + return(ACL_SYNTAX_ERR); + } else { /* then we have done all the processing */ - return 0; + return 0; } LDAP_UTF8INC(str); /* skip the "(" */ save = next; @@ -146,14 +146,50 @@ acl_parse(char * str, aci_t *aci_item, char **errbuf) if (aci_item->aci_type & ACI_TARGET_DN) { char *avaType; struct berval *avaValue; - const char *dn; - dn = slapi_sdn_get_ndn(aci_item->aci_sdn); - slapi_filter_get_ava(f, &avaType, &avaValue); + Slapi_DN *targdn = slapi_sdn_new(); + slapi_filter_get_ava ( f, &avaType, &avaValue ); + slapi_sdn_init_dn_byref(targdn, avaValue->bv_val); - if (!slapi_dn_issuffix(avaValue->bv_val, dn)) { + if (!slapi_sdn_get_dn(targdn)) { + /* not a valid DN */ + slapi_sdn_free(&targdn); return ACL_INVALID_TARGET; } + + if (!slapi_sdn_issuffix(targdn, aci_item->aci_sdn)) { + slapi_sdn_free(&targdn); + return ACL_INVALID_TARGET; + } + + if (slapi_sdn_compare(targdn, aci_item->aci_sdn)) { + int target_check = 0; + if (pb) { + slapi_pblock_get(pb, SLAPI_ACI_TARGET_CHECK, &target_check); + } + if (target_check != 1) { + /* Make sure that the target exists */ + int rc = 0; + Slapi_PBlock *temppb = slapi_pblock_new(); + slapi_search_internal_set_pb_ext(temppb, targdn, + LDAP_SCOPE_BASE, "(objectclass=*)", NULL, 1, NULL, NULL, + (void *)plugin_get_default_component_id(), 0); + slapi_search_internal_pb(temppb); + slapi_pblock_get(temppb, SLAPI_PLUGIN_INTOP_RESULT, &rc); + if (rc != LDAP_SUCCESS) { + slapi_log_error(SLAPI_LOG_FATAL, plugin_name, + "The ACL target %s does not exist\n", slapi_sdn_get_dn(targdn)); + } + + slapi_free_search_results_internal(temppb); + slapi_pblock_destroy(temppb); + if (pb) { + target_check = 1; + slapi_pblock_set(pb, SLAPI_ACI_TARGET_CHECK, &target_check); + } + } + } + slapi_sdn_free(&targdn); } } @@ -164,8 +200,8 @@ acl_parse(char * str, aci_t *aci_item, char **errbuf) ** */ if ((aci_item->aci_elevel != ACI_ELEVEL_USERDN_ANYONE) && - !(aci_item->aci_type & ACI_TARGET_MACRO_DN)) { - slapi_ch_free((void **)&aci_item->targetFilterStr); + !(aci_item->aci_type & ACI_TARGET_MACRO_DN)) { + slapi_ch_free((void **)&aci_item->targetFilterStr); } /* @@ -1550,6 +1586,7 @@ acl_strcpy_special (char *d, char *s) * verify if the aci's being added for the entry has a valid syntax or not. * * Input: +* Slapi_PBlock *pb - Parameter block * Slapi_Entry *e - The Slapi_Entry itself * char **errbuf; -- error message * @@ -1562,7 +1599,7 @@ acl_strcpy_special (char *d, char *s) * **************************************************************************/ int -acl_verify_aci_syntax (Slapi_Entry *e, char **errbuf) +acl_verify_aci_syntax (Slapi_PBlock *pb, Slapi_Entry *e, char **errbuf) { if (e != NULL) { @@ -1580,8 +1617,8 @@ acl_verify_aci_syntax (Slapi_Entry *e, char **errbuf) i= slapi_attr_first_value ( attr,&sval ); while ( i != -1 ) { - attrVal = slapi_value_get_berval ( sval ); - rv = acl_verify_syntax( e_sdn, attrVal, errbuf ); + attrVal = slapi_value_get_berval ( sval ); + rv = acl_verify_syntax( pb, e_sdn, attrVal, errbuf ); if ( 0 != rv ) { aclutil_print_err(rv, e_sdn, attrVal, errbuf); return ACL_ERR; @@ -1598,6 +1635,7 @@ acl_verify_aci_syntax (Slapi_Entry *e, char **errbuf) * added/replaced has the right syntax or not. * * Input: +* Slapi_PBlock *pb - Parameter block * Slapi_DN *e_sdn - sdn of the entry * berval *bval - The berval containg the aci value * @@ -1608,19 +1646,20 @@ acl_verify_aci_syntax (Slapi_Entry *e, char **errbuf) * None. * **************************************************************************/ + int -acl_verify_syntax(const Slapi_DN *e_sdn, - const struct berval *bval, char **errbuf) +acl_verify_syntax(Slapi_PBlock *pb, const Slapi_DN *e_sdn, + const struct berval *bval, char **errbuf) { aci_t *aci_item; - int rv = 0; + int rv = 0; char *str; aci_item = acllist_get_aci_new (); slapi_sdn_set_ndn_byval ( aci_item->aci_sdn, slapi_sdn_get_ndn ( e_sdn ) ); /* make a copy the the string */ - str = slapi_ch_strdup(bval->bv_val); - rv = acl_parse(str, aci_item, errbuf); + str = slapi_ch_strdup(bval->bv_val); + rv = acl_parse(pb, str, aci_item, errbuf); /* cleanup before you leave ... */ acllist_free_aci (aci_item); diff --git a/ldap/servers/slapd/pblock.c b/ldap/servers/slapd/pblock.c index bf9d71e6d..d3cc55c66 100644 --- a/ldap/servers/slapd/pblock.c +++ b/ldap/servers/slapd/pblock.c @@ -1953,6 +1953,12 @@ slapi_pblock_get( Slapi_PBlock *pblock, int arg, void *value ) (*(int *)value) = -1; } break; + + /* ACI Target Check */ + case SLAPI_ACI_TARGET_CHECK: + (*(int *)value) = pblock->pb_aci_target_check; + break; + default: LDAPDebug( LDAP_DEBUG_ANY, "Unknown parameter block argument %d\n", arg, 0, 0 ); @@ -3526,6 +3532,11 @@ slapi_pblock_set( Slapi_PBlock *pblock, int arg, void *value ) pblock->pb_paged_results_index = *(int *)value; break; + /* ACI Target Check */ + case SLAPI_ACI_TARGET_CHECK: + pblock->pb_aci_target_check = *((int *) value); + break; + default: LDAPDebug( LDAP_DEBUG_ANY, "Unknown parameter block argument %d\n", arg, 0, 0 ); diff --git a/ldap/servers/slapd/plugin_acl.c b/ldap/servers/slapd/plugin_acl.c index eebc292ed..e4a3a7661 100644 --- a/ldap/servers/slapd/plugin_acl.c +++ b/ldap/servers/slapd/plugin_acl.c @@ -217,7 +217,7 @@ plugin_call_acl_verify_syntax ( Slapi_PBlock *pb, Slapi_Entry *e, char **errbuf if (plugin_invoke_plugin_sdn (p, SLAPI_PLUGIN_ACL_SYNTAX_CHECK, pb, (Slapi_DN*)slapi_entry_get_sdn_const (e))){ plugin_called = 1; - rc = (*p->plg_acl_syntax_check)( e, errbuf ); + rc = (*p->plg_acl_syntax_check)( pb, e, errbuf ); if ( rc != LDAP_SUCCESS ) break; } } diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index c4acb604d..88f1791aa 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1745,6 +1745,10 @@ typedef struct slapi_pblock { int pb_paged_results_index; /* stash SLAPI_PAGED_RESULTS_INDEX */ passwdPolicy *pwdpolicy; void *op_stack_elem; + + /* For ACI Target Check */ + int pb_aci_target_check; /* this flag prevents duplicate checking of ACI's target existence */ + } slapi_pblock; /* index if substrlens */ diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index 830901283..6cb6d744e 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -6989,6 +6989,9 @@ typedef struct slapi_plugindesc { /* Simple paged results index */ #define SLAPI_PAGED_RESULTS_INDEX 1945 +/* ACI Target Check */ +#define SLAPI_ACI_TARGET_CHECK 1946 + /* convenience macros for checking modify operation types */ #define SLAPI_IS_MOD_ADD(x) (((x) & ~LDAP_MOD_BVALUES) == LDAP_MOD_ADD) #define SLAPI_IS_MOD_DELETE(x) (((x) & ~LDAP_MOD_BVALUES) == LDAP_MOD_DELETE)
0
2293103daf0f77a970c387c7330c9416b09452bc
389ds/389-ds-base
Issue 5368 - Retro Changelog trimming does not work (#5486) Bug description: After an initial trimming, the trimming thread is not scheduled according to nsslapd-changelog-trim-interval. It is erroneously scheduled according to nsslapd-changelogmaxage. Fix description: Get the trimming interval into 'ts' (trimming structure) and decide to trim according to nsslapd-changelogmaxage relates: #5368 Reviewed by: Mark Reynolds, Simon Pichugin (thanks)
commit 2293103daf0f77a970c387c7330c9416b09452bc Author: tbordaz <[email protected]> Date: Fri Oct 14 16:00:12 2022 +0200 Issue 5368 - Retro Changelog trimming does not work (#5486) Bug description: After an initial trimming, the trimming thread is not scheduled according to nsslapd-changelog-trim-interval. It is erroneously scheduled according to nsslapd-changelogmaxage. Fix description: Get the trimming interval into 'ts' (trimming structure) and decide to trim according to nsslapd-changelogmaxage relates: #5368 Reviewed by: Mark Reynolds, Simon Pichugin (thanks) diff --git a/dirsrvtests/tests/suites/retrocl/basic_test.py b/dirsrvtests/tests/suites/retrocl/basic_test.py index 3bdff9415..85d6b08e7 100644 --- a/dirsrvtests/tests/suites/retrocl/basic_test.py +++ b/dirsrvtests/tests/suites/retrocl/basic_test.py @@ -329,6 +329,95 @@ def test_retrocl_trimming(topology_st): # Clean up inst.config.set('nsslapd-errorlog-level', '0') +def test_retrocl_trimming_interval(topology_st, request): + """Test retrocl trimming interval works + + :id: 261a951d-8fe3-4b94-b933-c21806f795e7 + :setup: Standalone Instance + :steps: + 1. Enable Retro changelog + 2. Configure trimming (trimming records older than 20sec) + 3. Do a dummy update and wait 5sec + 4. Do a extra updates + 5. wait for 10sec and restart (after restart the dummy update will soon be trimmed) + 6. wait 15sec so that the extra updates are trimmed + 7. stop the instance + 8. check that dummy/extra updates have been trimmed + :expectedresults: + 1. Success + 2. Success + 3. Success + 4. Success + 5. Success + 6. Success + 7. Success + 8. Success + """ + + inst = topology_st.standalone + # Configure plugin + log.info('Configure retrocl plugin') + rcl = RetroChangelogPlugin(inst) + rcl.replace('nsslapd-include-suffix', DEFAULT_SUFFIX) + rcl.enable() + inst.restart() + + # Do some updates + suffix = Domain(inst, DEFAULT_SUFFIX) + + # Configure trimming + rcl.replace('nsslapd-changelog-trim-interval', '2') + rcl.replace('nsslapd-changelogmaxage', '20s') + inst.restart() + + # this update will be the first one to be trimmed + # and will initialize in the last_trim time. + # This initialization is important to trigger the bug + # if not initialized it will trim immediately + suffix.replace('description', 'dummy') + + # retrieve the index of the update in retroCL as + # starting point for the extra updates + try: + retro_changelog_suffix = DSLdapObjects(inst, basedn=RETROCL_SUFFIX) + cl_index = int(str(retro_changelog_suffix.filter(f'(targetDn={DEFAULT_SUFFIX})')[0].get_attr_vals_utf8('changeNumber')[0])) + except ldap.LDAPError as e: + log.fatal("Changelog search failed, error: " + str(e)) + assert False + time.sleep(5) + + # Those extra updates should be trimmed 5 sec after the previous one + for idx in range(0, 10): + suffix.replace('description', str(idx)) + + # wait for ~14s (sleep+stop+start), so the trimming + # of the first update occurs soon after the restart + time.sleep(10) + inst.config.set('nsslapd-plugin-logging', 'on') + inst.config.set('nsslapd-accesslog-level','260') + inst.stop() + inst.start() + + # wait for an additional 15s. + # at that time we should have trim the extra updates + # checking both error logs and DEL operations in access logs + inst.config.set('nsslapd-errorlog-level', '65536') # plugin logging + time.sleep(15) + inst.stop() + assert inst.searchErrorsLog("trim_changelog: removed 9 change records") + for idx in range(cl_index+1,cl_index+10): + pattern="changenumber=%d,cn=changelog" % idx + assert inst.searchAccessLog(pattern) + + # Clean up + inst.restart() + + def fin(): + inst.config.set('nsslapd-errorlog-level', '0') + inst.config.set('nsslapd-plugin-logging', 'off') + inst.config.set('nsslapd-accesslog-level','256') + + request.addfinalizer(fin) if __name__ == '__main__': # Run isolated diff --git a/ldap/servers/plugins/retrocl/retrocl_trim.c b/ldap/servers/plugins/retrocl/retrocl_trim.c index ee2adf2dd..37e5fbea7 100644 --- a/ldap/servers/plugins/retrocl/retrocl_trim.c +++ b/ldap/servers/plugins/retrocl/retrocl_trim.c @@ -17,13 +17,13 @@ typedef struct _trim_status { time_t ts_c_max_age; /* Constraint - max age of a changelog entry */ + int ts_c_trim_interval; /* Constraint - interval to evaluate the need to trim */ time_t ts_s_last_trim; /* Status - last time we trimmed */ int ts_s_initialized; /* Status - non-zero if initialized */ int ts_s_trimming; /* non-zero if trimming in progress */ PRLock *ts_s_trim_mutex; /* protects ts_s_trimming */ } trim_status; static trim_status ts = {0L, 0L, 0, 0, NULL}; -static int trim_interval = DEFAULT_CHANGELOGDB_TRIM_INTERVAL; /* in second */ /* * All standard changeLogEntry attributes (initialized in get_cleattrs) @@ -239,12 +239,13 @@ trim_changelog(void) time_t now_maxage; /* used for checking if the changelog entry can be trimmed */ changeNumber first_in_log = 0, last_in_log = 0; int num_deleted = 0; - int max_age, last_trim; + int max_age, last_trim, trim_interval; now_interval = slapi_current_rel_time_t(); /* monotonic time for interval */ PR_Lock(ts.ts_s_trim_mutex); max_age = ts.ts_c_max_age; + trim_interval = ts.ts_c_trim_interval; last_trim = ts.ts_s_last_trim; PR_Unlock(ts.ts_s_trim_mutex); @@ -366,7 +367,7 @@ retrocl_housekeeping(time_t cur_time, void *noarg __attribute__((unused))) int must_trim = 0; /* See if we need to trim */ /* Has enough time elapsed since our last check? */ - if (cur_time - ts.ts_s_last_trim >= (ts.ts_c_max_age)) { + if (cur_time - ts.ts_s_last_trim >= (ts.ts_c_trim_interval)) { /* Is the first entry too old? */ time_t first_time; time_t now_maxage = slapi_current_utc_time(); /* real time for trimming candidates */ @@ -422,6 +423,7 @@ retrocl_init_trimming(void) const char *cl_maxage; time_t ageval = 0; /* Don't trim, by default */ const char *cl_trim_interval; + int trim_interval; cl_maxage = retrocl_get_config_str(CONFIG_CHANGELOG_MAXAGE_ATTRIBUTE); if (cl_maxage) { @@ -441,7 +443,7 @@ retrocl_init_trimming(void) cl_trim_interval = retrocl_get_config_str(CONFIG_CHANGELOG_TRIM_INTERVAL); if (cl_trim_interval) { trim_interval = strtol(cl_trim_interval, (char **)NULL, 10); - if (0 == trim_interval) { + if (0 >= trim_interval) { slapi_log_err(SLAPI_LOG_ERR, RETROCL_PLUGIN_NAME, "retrocl_init_trimming: ignoring invalid %s value %s; " "resetting the default %d\n", @@ -453,6 +455,7 @@ retrocl_init_trimming(void) } ts.ts_c_max_age = ageval; + ts.ts_c_trim_interval = trim_interval; ts.ts_s_last_trim = (time_t)0L; ts.ts_s_trimming = 0; if ((ts.ts_s_trim_mutex = PR_NewLock()) == NULL) { @@ -466,7 +469,7 @@ retrocl_init_trimming(void) retrocl_trim_ctx = slapi_eq_repeat_rel(retrocl_housekeeping, NULL, (time_t)0, /* in milliseconds */ - trim_interval * 1000); + ts.ts_c_trim_interval * 1000); } /*
0
a9a5a5d9fe0801988f51a77b4b11029349f67c10
389ds/389-ds-base
Bug 602531 - coverity: op_shared_delete: compare preop entry and GLUE_PARENT_ENTRY before freeing them https://bugzilla.redhat.com/show_bug.cgi?id=602531 Resolves: bug 602531 Bug Description: coverity: op_shared_delete: compare preop entry and GLUE_PARENT_ENTRY before freeing them Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: Get the pre entry and glue parent entries separately, compare them, and only free one of them if they are the same. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no
commit a9a5a5d9fe0801988f51a77b4b11029349f67c10 Author: Rich Megginson <[email protected]> Date: Wed Jun 30 14:40:34 2010 -0600 Bug 602531 - coverity: op_shared_delete: compare preop entry and GLUE_PARENT_ENTRY before freeing them https://bugzilla.redhat.com/show_bug.cgi?id=602531 Resolves: bug 602531 Bug Description: coverity: op_shared_delete: compare preop entry and GLUE_PARENT_ENTRY before freeing them Reviewed by: nhosoi (Thanks!) Branch: HEAD Fix Description: Get the pre entry and glue parent entries separately, compare them, and only free one of them if they are the same. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/delete.c b/ldap/servers/slapd/delete.c index acb2e440e..16d929376 100644 --- a/ldap/servers/slapd/delete.c +++ b/ldap/servers/slapd/delete.c @@ -372,15 +372,20 @@ static void op_shared_delete (Slapi_PBlock *pb) } free_and_return: - if (be) + if (be) { slapi_be_Unlock(be); - slapi_pblock_get(pb, SLAPI_ENTRY_PRE_OP, &ecopy); - slapi_entry_free(ecopy); - slapi_pblock_get ( pb, SLAPI_DELETE_GLUE_PARENT_ENTRY, &ecopy ); - if (ecopy) + } { - slapi_entry_free (ecopy); - slapi_pblock_set (pb, SLAPI_DELETE_GLUE_PARENT_ENTRY, NULL); + Slapi_Entry *epre = NULL, *eparent = NULL; + slapi_pblock_get(pb, SLAPI_ENTRY_PRE_OP, &epre); + slapi_pblock_get(pb, SLAPI_DELETE_GLUE_PARENT_ENTRY, &eparent); + slapi_pblock_set(pb, SLAPI_ENTRY_PRE_OP, NULL); + slapi_pblock_set(pb, SLAPI_DELETE_GLUE_PARENT_ENTRY, NULL); + if (epre == eparent) { + eparent = NULL; + } + slapi_entry_free(epre); + slapi_entry_free(eparent); } slapi_pblock_get(pb, SLAPI_URP_NAMING_COLLISION_DN, &dn); slapi_ch_free((void **)&dn);
0
9382319e96f06eb941380adb36cfbae1927ecb08
389ds/389-ds-base
Ticket #47843 - Fix various typos in manpages & code Description: Fix various typos Author: Benjamin Drung <[email protected]> https://fedorahosted.org/389/ticket/47843 Reviewed by [email protected]
commit 9382319e96f06eb941380adb36cfbae1927ecb08 Author: Noriko Hosoi <[email protected]> Date: Thu Jul 10 15:10:29 2014 -0700 Ticket #47843 - Fix various typos in manpages & code Description: Fix various typos Author: Benjamin Drung <[email protected]> https://fedorahosted.org/389/ticket/47843 Reviewed by [email protected] diff --git a/ldap/servers/plugins/acl/acllist.c b/ldap/servers/plugins/acl/acllist.c index 88ccb3a9a..668ef58c3 100644 --- a/ldap/servers/plugins/acl/acllist.c +++ b/ldap/servers/plugins/acl/acllist.c @@ -149,7 +149,7 @@ void acl_be_state_change_fnc ( void *handle, char *be_name, int old_state, if ( (be = slapi_be_select_by_instance_name( be_name )) == NULL) { slapi_log_error ( SLAPI_LOG_ACL, plugin_name, - "Failed to retreive backend--NOT activating it's acis\n"); + "Failed to retrieve backend--NOT activating it's acis\n"); return; } @@ -159,7 +159,7 @@ void acl_be_state_change_fnc ( void *handle, char *be_name, int old_state, if ( (sdn = slapi_be_getsuffix( be, 0)) == NULL ) { slapi_log_error ( SLAPI_LOG_ACL, plugin_name, - "Failed to retreive backend--NOT activating it's acis\n"); + "Failed to retrieve backend--NOT activating it's acis\n"); return; } @@ -176,7 +176,7 @@ void acl_be_state_change_fnc ( void *handle, char *be_name, int old_state, if ( (be = slapi_be_select_by_instance_name( be_name )) == NULL) { slapi_log_error ( SLAPI_LOG_ACL, plugin_name, - "Failed to retreive backend--NOT activating it's acis\n"); + "Failed to retrieve backend--NOT activating it's acis\n"); return; } @@ -186,7 +186,7 @@ void acl_be_state_change_fnc ( void *handle, char *be_name, int old_state, if ( (sdn = slapi_be_getsuffix( be, 0)) == NULL ) { slapi_log_error ( SLAPI_LOG_ACL, plugin_name, - "Failed to retreive backend--NOT activating it's acis\n"); + "Failed to retrieve backend--NOT activating it's acis\n"); return; } diff --git a/ldap/servers/plugins/distrib/Makefile b/ldap/servers/plugins/distrib/Makefile index 4dd83674e..60e9ad63a 100644 --- a/ldap/servers/plugins/distrib/Makefile +++ b/ldap/servers/plugins/distrib/Makefile @@ -72,7 +72,7 @@ endif # The sample distribution plugin is not part of DS. # So we generate the shared library outside of $(LIBDIR) -# so that it's not retreived by the packaging makefiles. +# so that it's not retrieved by the packaging makefiles. #LIBDIS = $(addprefix $(LIBDIR)/, $(DIS_DLL).$(DLL_SUFFIX)) LIBDIS = $(addprefix $(OBJDEST)/, $(DIS_DLL).$(DLL_SUFFIX)) diff --git a/ldap/servers/plugins/posix-winsync/posix-winsync-config.c b/ldap/servers/plugins/posix-winsync/posix-winsync-config.c index 81f2b6dbb..4234080e1 100644 --- a/ldap/servers/plugins/posix-winsync/posix-winsync-config.c +++ b/ldap/servers/plugins/posix-winsync/posix-winsync-config.c @@ -263,7 +263,7 @@ posix_winsync_apply_config(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Ent if (!slapi_entry_attr_find(e, POSIX_WINSYNC_MSSFU_SCHEMA, &testattr) && (NULL != testattr)) { mssfuSchema = slapi_entry_attr_get_bool(e, POSIX_WINSYNC_MSSFU_SCHEMA); slapi_log_error(SLAPI_LOG_PLUGIN, POSIX_WINSYNC_PLUGIN_NAME, - "_apply_config: Config paramter %s: %d\n", POSIX_WINSYNC_MSSFU_SCHEMA, + "_apply_config: Config parameter %s: %d\n", POSIX_WINSYNC_MSSFU_SCHEMA, mssfuSchema); } @@ -271,7 +271,7 @@ posix_winsync_apply_config(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Ent if (!slapi_entry_attr_find(e, POSIX_WINSYNC_MAP_MEMBERUID, &testattr) && (NULL != testattr)) { mapMemberUID = slapi_entry_attr_get_bool(e, POSIX_WINSYNC_MAP_MEMBERUID); slapi_log_error(SLAPI_LOG_PLUGIN, POSIX_WINSYNC_PLUGIN_NAME, - "_apply_config: Config paramter %s: %d\n", POSIX_WINSYNC_MAP_MEMBERUID, + "_apply_config: Config parameter %s: %d\n", POSIX_WINSYNC_MAP_MEMBERUID, mapMemberUID); } /* get create task value */ @@ -279,21 +279,21 @@ posix_winsync_apply_config(Slapi_PBlock *pb, Slapi_Entry* entryBefore, Slapi_Ent != testattr)) { createMemberOfTask = slapi_entry_attr_get_bool(e, POSIX_WINSYNC_CREATE_MEMBEROFTASK); slapi_log_error(SLAPI_LOG_PLUGIN, POSIX_WINSYNC_PLUGIN_NAME, - "_apply_config: Config paramter %s: %d\n", + "_apply_config: Config parameter %s: %d\n", POSIX_WINSYNC_CREATE_MEMBEROFTASK, createMemberOfTask); } /* get lower case UID in memberUID */ if (!slapi_entry_attr_find(e, POSIX_WINSYNC_LOWER_CASE, &testattr) && (NULL != testattr)) { lowercase = slapi_entry_attr_get_bool(e, POSIX_WINSYNC_LOWER_CASE); slapi_log_error(SLAPI_LOG_PLUGIN, POSIX_WINSYNC_PLUGIN_NAME, - "_apply_config: Config paramter %s: %d\n", POSIX_WINSYNC_LOWER_CASE, + "_apply_config: Config parameter %s: %d\n", POSIX_WINSYNC_LOWER_CASE, lowercase); } /* propogate memberuids in nested grouping */ if (!slapi_entry_attr_find(e, POSIX_WINSYNC_MAP_NESTED_GROUPING, &testattr) && (NULL != testattr)) { mapNestedGrouping = slapi_entry_attr_get_bool(e, POSIX_WINSYNC_MAP_NESTED_GROUPING); slapi_log_error(SLAPI_LOG_PLUGIN, POSIX_WINSYNC_PLUGIN_NAME, - "_apply_config: Config paramter %s: %d\n", POSIX_WINSYNC_MAP_NESTED_GROUPING, + "_apply_config: Config parameter %s: %d\n", POSIX_WINSYNC_MAP_NESTED_GROUPING, mapNestedGrouping); } /* if we got here, we have valid values for everything diff --git a/ldap/servers/plugins/replication/urp.c b/ldap/servers/plugins/replication/urp.c index d867274e1..cecf95cd1 100644 --- a/ldap/servers/plugins/replication/urp.c +++ b/ldap/servers/plugins/replication/urp.c @@ -1094,7 +1094,7 @@ urp_annotate_dn (char *sessionid, const Slapi_Entry *entry, CSN *opcsn, const ch } /* - * An URP Naming Collision helper function. Retreives a list of entries + * An URP Naming Collision helper function. Retrieves a list of entries * that have the given dn excluding the unique id of the entry. Any * entries returned will be entries that have been added with the same * dn, but caused a naming conflict when replicated. The URP to fix diff --git a/ldap/servers/plugins/syntaxes/facsimile.c b/ldap/servers/plugins/syntaxes/facsimile.c index cb57f1e5b..96200f1e4 100644 --- a/ldap/servers/plugins/syntaxes/facsimile.c +++ b/ldap/servers/plugins/syntaxes/facsimile.c @@ -241,7 +241,7 @@ facsimile_validate( } /* We're guaranteed to have at least one character - * past p. This is where the fax-paramter should + * past p. This is where the fax-parameter should * start. */ start = p + 1; @@ -258,9 +258,9 @@ facsimile_validate( } /* We're guaranteed to have another character, which - * should be the beginning of the next fax-paramter. + * should be the beginning of the next fax-parameter. * Adjust the start pointer to point to the beginning - * of this fax-paramter. */ + * of this fax-parameter. */ start = p + 1; } } diff --git a/ldap/servers/slapd/passwd_extop.c b/ldap/servers/slapd/passwd_extop.c index 999a7af20..9b76e6dee 100644 --- a/ldap/servers/slapd/passwd_extop.c +++ b/ldap/servers/slapd/passwd_extop.c @@ -187,7 +187,7 @@ passwd_apply_mods(Slapi_PBlock *pb_orig, const Slapi_DN *sdn, Slapi_Mods *mods, slapi_pblock_get(&pb, SLAPI_PLUGIN_INTOP_RESULT, &ret); - /* Retreive and duplicate the response controls since they will be + /* Retrieve and duplicate the response controls since they will be * destroyed along with the pblock used for the internal operation. */ slapi_pblock_get(&pb, SLAPI_RESCONTROLS, &pb_resp_controls); if (pb_resp_controls) { diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index b83b08a04..71d239ac0 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -1644,9 +1644,9 @@ int slapi_entry_schema_check_ext( Slapi_PBlock *pb, Slapi_Entry *e, int check_re * \return \c 1 if the entry has any attribute values that violate the syntax rules * imposed by the associated attribute type. If the \c pb parameter was * passed in, an error message describing the syntax violations will be - * set in the #SLAPI_PB_RESULT_TEXT paramter. + * set in the #SLAPI_PB_RESULT_TEXT parameter. * \warning The \c pb parameter can be \c NULL. It is used to store an error - * message with details of any syntax violations. The \c pb paramter + * message with details of any syntax violations. The \c pb parameter * is also used to check if the #SLAPI_IS_REPLICATED_OPERATION flag is * set. If that flag is present, no syntax checking is performed. */ @@ -1665,7 +1665,7 @@ int slapi_entry_syntax_check( Slapi_PBlock *pb, Slapi_Entry *e, int override ); * parameter was passed in, an error message will be set in the * #SLAPI_PB_RESULT_TEXT parameter. * \warning The \c pb parameter can be \c NULL. It is used to store an error - * message with details of any syntax violations. The \c pb paramter + * message with details of any syntax violations. The \c pb parameter * is also used to check if the #SLAPI_IS_REPLICATED_OPERATION flag is * set. If that flag is present, no syntax checking is performed. */ @@ -1684,9 +1684,9 @@ int slapi_dn_syntax_check( Slapi_PBlock *pb, const char *dn, int override ); * \return \c 1 if the mods are adding any new attribute values that violate the * syntax rules imposed by the associated attribute type. If the \c pb * parameter was passed in, an error message describing the syntax violations - * will be set in the #SLAPI_PB_RESULT_TEXT paramter. + * will be set in the #SLAPI_PB_RESULT_TEXT parameter. * \warning The \c pb parameter can be \c NULL. It is used to store an error - * message with details of any syntax violations. The \c pb paramter + * message with details of any syntax violations. The \c pb parameter * is also used to check if the #SLAPI_IS_REPLICATED_OPERATION flag is * set. If that flag is present, no syntax checking is performed. */ @@ -2975,7 +2975,7 @@ int slapi_sdn_scope_test( const Slapi_DN *dn, const Slapi_DN *base, int scope ); int slapi_sdn_scope_test_ext( const Slapi_DN *dn, const Slapi_DN *base, int scope, int flags ); /** - * Retreives the RDN from a given DN. + * Retrieves the RDN from a given DN. * * This function takes the DN stored in the \c Slapi_DN structure pointed to * by \c sdn and fills in it's RDN within the \c Slapi_RDN structure pointed @@ -4635,7 +4635,7 @@ Slapi_Value *slapi_value_set_berval( Slapi_Value *value, const struct berval *bv * the value. * \param vfrom Pointer to the \c Slapi_Value structure from which to * get the value. - * \return Pointer to the \c Slapi_Value structure passed as the \c value paramter. + * \return Pointer to the \c Slapi_Value structure passed as the \c value parameter. * \return \c NULL if the \c value parameter was \c NULL. * \warning The \c vfrom parameter must not be \c NULL. * \warning If the pointer to the \c Slapi_Value structure is \c NULL, diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 3fbdb44ea..2347119e1 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -957,7 +957,7 @@ enum {UID_SUCCESS, /* operation was successfull */ /* Function: slapi_uniqueIDNew Description: allocates new id - Paramters: none + Parameters: none Return: pointer to the newly allocated id if successful NULL if the system is out of memory */ diff --git a/ldap/servers/slapd/slapi_counter.c b/ldap/servers/slapd/slapi_counter.c index 4d2c5cf3b..fe14e2d43 100644 --- a/ldap/servers/slapd/slapi_counter.c +++ b/ldap/servers/slapd/slapi_counter.c @@ -382,7 +382,7 @@ PRUint64 slapi_counter_get_value(Slapi_Counter *counter) * replace *ptr with ECX:EBX */ " lock; cmpxchg8b %0;" " jnz retryget;" - /* Put retreived value into value */ + /* Put retrieved value into value */ " movl %%ebx, %1;" " movl %%ecx, 4%1;" #ifdef CPU_x86 diff --git a/ldap/servers/slapd/test-plugins/Makefile.server b/ldap/servers/slapd/test-plugins/Makefile.server index d055ddd85..3e1ab7fec 100644 --- a/ldap/servers/slapd/test-plugins/Makefile.server +++ b/ldap/servers/slapd/test-plugins/Makefile.server @@ -72,7 +72,7 @@ endif # The sample distribution plugin is not part of DS. # So we generate the shared library outside of $(LIBDIR) -# so that it's not retreived by the packaging makefiles. +# so that it's not retrieved by the packaging makefiles. #LIBDIS = $(addprefix $(LIBDIR)/, $(DIS_DLL).$(DLL_SUFFIX)) LIBDIS = $(addprefix $(OBJDEST)/, $(TEST_PLUGIN_DLL).$(DLL_SUFFIX)) diff --git a/ldap/servers/slapd/tools/ldclt/data.c b/ldap/servers/slapd/tools/ldclt/data.c index 45016d8f2..590f29a3d 100644 --- a/ldap/servers/slapd/tools/ldclt/data.c +++ b/ldap/servers/slapd/tools/ldclt/data.c @@ -51,7 +51,7 @@ DESCRIPTION : This file implements the management of the data that are manipulated by ldclt. - It is targetted to contain all the functions needed for + It is targeted to contain all the functions needed for the images, etc... LOCAL : None. HISTORY : diff --git a/ldap/servers/slapd/tools/ldclt/ldapfct.c b/ldap/servers/slapd/tools/ldclt/ldapfct.c index c57f240c2..235e20c7d 100644 --- a/ldap/servers/slapd/tools/ldclt/ldapfct.c +++ b/ldap/servers/slapd/tools/ldclt/ldapfct.c @@ -278,7 +278,7 @@ int ldclt_alloc_ber( LDAP *ld, BerElement **berp ); /* **************************************************************************** FUNCTION : my_ldap_err2string - PURPOSE : This function is targetted to encapsulate the standard + PURPOSE : This function is targeted to encapsulate the standard function ldap_err2string(), that sometimes returns a NULL pointer and thus crashes the appicaliton :-( INPUT : err = error to decode diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.c b/ldap/servers/slapd/tools/ldclt/ldclt.c index 4fb8b2500..2ccba822e 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.c +++ b/ldap/servers/slapd/tools/ldclt/ldclt.c @@ -50,10 +50,10 @@ DATE : 03 December 1998 DESCRIPTION : This file is the main file of the ldclt tool. This tool - is targetted to be a multi-threaded ldap client, + is targeted to be a multi-threaded ldap client, specially designed to ensure good reliability of both the basic ldap server purpose, and the replication - processes. It is *not* targetted against the + processes. It is *not* targeted against the functionnality aspect of the product, but rather on the stress and long-term operation. LOCAL : None. @@ -672,7 +672,7 @@ runThem (void) /* New function */ /*JLS 17-11-00*/ /* **************************************************************************** FUNCTION : shutdownThreads - PURPOSE : This function is targetted to shutdown the threads. + PURPOSE : This function is targeted to shutdown the threads. INPUT : None. OUTPUT : None. RETURN : -1 if error, 0 else. @@ -1750,7 +1750,7 @@ basicInit (void) /* **************************************************************************** FUNCTION : printModeValues - PURPOSE : This function is targetted to print the bits mask of + PURPOSE : This function is targeted to print the bits mask of the mode field. INPUT : None. OUTPUT : None. diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.h b/ldap/servers/slapd/tools/ldclt/ldclt.h index 71ff06d81..d2c44b3e3 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.h +++ b/ldap/servers/slapd/tools/ldclt/ldclt.h @@ -612,7 +612,7 @@ typedef struct main_context { * This structure is aimed to ease the managing of asynchronous * operations, keeping in memory the msgid returned by the library and * a free string meaning something for the user. - * It is targetted that this string is something like a DN, and is + * It is targeted that this string is something like a DN, and is * locally managed by the list functions. */ typedef struct msgid_cell { @@ -625,7 +625,7 @@ typedef struct msgid_cell { /* * This structure contain the context associated with each thread. - * It is targetted to be initiated by the main thread, and maintained + * It is targeted to be initiated by the main thread, and maintained * by each thread. */ typedef struct thread_context { diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.man b/ldap/servers/slapd/tools/ldclt/ldclt.man index 088e90486..8a3e1dec9 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.man +++ b/ldap/servers/slapd/tools/ldclt/ldclt.man @@ -21,7 +21,7 @@ AVAILABILITY SUNQAldap DESCRIPTION - ldclt is a multi-threaded test tool targetted to stress a + ldclt is a multi-threaded test tool targeted to stress a ldap server with multiple simultaneous requests. The tool automatically set its ulimit parameters to fit diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.use b/ldap/servers/slapd/tools/ldclt/ldclt.use index 96136909e..6933f2a9d 100644 --- a/ldap/servers/slapd/tools/ldclt/ldclt.use +++ b/ldap/servers/slapd/tools/ldclt/ldclt.use @@ -9,7 +9,7 @@ usage: ldclt [-qQvV] [-E <max errors>] [-S <slave>] [-P<master port>] [-W <waitsec>] [-Z <certfile>] - This tool is a ldap client targetted to validate the reliability of + This tool is a ldap client targeted to validate the reliability of the product under test under hard use. The valid options are: diff --git a/ldap/servers/slapd/tools/ldclt/ldcltU.c b/ldap/servers/slapd/tools/ldclt/ldcltU.c index e436e18a0..67fa952c8 100644 --- a/ldap/servers/slapd/tools/ldclt/ldcltU.c +++ b/ldap/servers/slapd/tools/ldclt/ldcltU.c @@ -56,7 +56,7 @@ * [-S <slave>] [-P<master port>] * [-W <waitsec>] [-Z <certfile>] * - * This tool is a ldap client targetted to validate the reliability of + * This tool is a ldap client targeted to validate the reliability of * the product under test under hard use. * * The valid options are: @@ -158,7 +158,7 @@ void usage () (void) printf (" [-S <slave>] [-P<master port>]\n"); (void) printf (" [-W <waitsec>] [-Z <certfile>]\n"); (void) printf ("\n"); - (void) printf (" This tool is a ldap client targetted to validate the reliability of\n"); + (void) printf (" This tool is a ldap client targeted to validate the reliability of\n"); (void) printf (" the product under test under hard use.\n"); (void) printf ("\n"); (void) printf (" The valid options are:\n"); diff --git a/ldap/servers/slapd/tools/ldclt/opCheck.c b/ldap/servers/slapd/tools/ldclt/opCheck.c index e41ba30db..aa7f78072 100644 --- a/ldap/servers/slapd/tools/ldclt/opCheck.c +++ b/ldap/servers/slapd/tools/ldclt/opCheck.c @@ -240,7 +240,7 @@ LDAPMod2attributes ( /* **************************************************************************** FUNCTION : freeAttributesArray - PURPOSE : This function is targetted to free an array of + PURPOSE : This function is targeted to free an array of struct attribute. It does not free the array itself, but only the types and values memorized in it. INPUT : attribs = array to free. diff --git a/ldap/servers/slapd/tools/ldclt/workarounds.c b/ldap/servers/slapd/tools/ldclt/workarounds.c index 5275e6de6..f0b83750d 100644 --- a/ldap/servers/slapd/tools/ldclt/workarounds.c +++ b/ldap/servers/slapd/tools/ldclt/workarounds.c @@ -49,7 +49,7 @@ VERSION : 1.0 DATE : 15 December 1998 DESCRIPTION : - This file contains special work-arounds targetted to + This file contains special work-arounds targeted to fix, or work-around, the various bugs that may appear in Solaris 2.7 libldap. LOCAL : None. diff --git a/lib/libaccess/acltools.cpp b/lib/libaccess/acltools.cpp index 3fa8a7dac..21645fb96 100644 --- a/lib/libaccess/acltools.cpp +++ b/lib/libaccess/acltools.cpp @@ -436,7 +436,7 @@ acl_comp_string( CmpOp_t cmp ) * attr_name Term Attribute name * cmp Comparison operator * attr_pattern Pattern for comparison - * Ouput: + * Output: * acl_expr New term added * Returns: * 0 Success @@ -518,7 +518,7 @@ ACLExprRaw_t *raw_expr; * Input: * errp The error stack * acl_expr The expression to negate - * Ouput + * Output * acl_expr The negated expression * Returns: * 0 Success diff --git a/man/man8/bak2db.pl.8 b/man/man8/bak2db.pl.8 index 25c87dbb1..92e474692 100644 --- a/man/man8/bak2db.pl.8 +++ b/man/man8/bak2db.pl.8 @@ -58,7 +58,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/cleanallruv.pl.8 b/man/man8/cleanallruv.pl.8 index dc49bad55..241b7993e 100644 --- a/man/man8/cleanallruv.pl.8 +++ b/man/man8/cleanallruv.pl.8 @@ -61,7 +61,7 @@ Abort a cleanAllRUV task that is currently running. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/db2bak.pl.8 b/man/man8/db2bak.pl.8 index 68072921b..df6af3dd8 100644 --- a/man/man8/db2bak.pl.8 +++ b/man/man8/db2bak.pl.8 @@ -56,7 +56,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/db2index.pl.8 b/man/man8/db2index.pl.8 index ebb5847f1..3df7aba88 100644 --- a/man/man8/db2index.pl.8 +++ b/man/man8/db2index.pl.8 @@ -59,7 +59,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/db2ldif.pl.8 b/man/man8/db2ldif.pl.8 index 139ae8b59..59f9b8605 100644 --- a/man/man8/db2ldif.pl.8 +++ b/man/man8/db2ldif.pl.8 @@ -100,7 +100,7 @@ Deletes, for reasons of backward compatibility, the first line of the LDIF file .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/fixup-linkedattrs.pl.8 b/man/man8/fixup-linkedattrs.pl.8 index 1c77abaf7..82aa09874 100644 --- a/man/man8/fixup-linkedattrs.pl.8 +++ b/man/man8/fixup-linkedattrs.pl.8 @@ -52,7 +52,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/fixup-memberof.pl.8 b/man/man8/fixup-memberof.pl.8 index 7716a5892..aa25043fb 100644 --- a/man/man8/fixup-memberof.pl.8 +++ b/man/man8/fixup-memberof.pl.8 @@ -56,7 +56,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/ldif2db.8 b/man/man8/ldif2db.8 index 69aadb262..7736bc2bf 100644 --- a/man/man8/ldif2db.8 +++ b/man/man8/ldif2db.8 @@ -63,7 +63,7 @@ Encrypts data during import. This option is used only if database encryption is .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/ldif2db.pl.8 b/man/man8/ldif2db.pl.8 index 67e0d2d48..b6d9e8d88 100644 --- a/man/man8/ldif2db.pl.8 +++ b/man/man8/ldif2db.pl.8 @@ -78,7 +78,7 @@ The number of entries to process before starting a fresh pass during the import. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/ns-newpwpolicy.pl.8 b/man/man8/ns-newpwpolicy.pl.8 index 34cb15b26..c31e75d41 100644 --- a/man/man8/ns-newpwpolicy.pl.8 +++ b/man/man8/ns-newpwpolicy.pl.8 @@ -61,7 +61,7 @@ Specifies the DN of the suffix entry that needs to be updated with subtree-level .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .SH EXAMPLE .TP ns-newpwpolicy.pl -Z instance3 -D 'cn=directory manager' -w password -P STARTTLS -U 'uid=user,ou=people,dc=example,dc=com' diff --git a/man/man8/schema-reload.pl.8 b/man/man8/schema-reload.pl.8 index d14868530..bb21dd665 100644 --- a/man/man8/schema-reload.pl.8 +++ b/man/man8/schema-reload.pl.8 @@ -52,7 +52,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/syntax-validate.pl.8 b/man/man8/syntax-validate.pl.8 index 3bd0d1071..37c034bc1 100644 --- a/man/man8/syntax-validate.pl.8 +++ b/man/man8/syntax-validate.pl.8 @@ -55,7 +55,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br diff --git a/man/man8/usn-tombstone-cleanup.pl.8 b/man/man8/usn-tombstone-cleanup.pl.8 index 175e973ee..6b3149284 100644 --- a/man/man8/usn-tombstone-cleanup.pl.8 +++ b/man/man8/usn-tombstone-cleanup.pl.8 @@ -58,7 +58,7 @@ available for the root user. .TP .B \fB\-v\fR .br -Display verbose ouput +Display verbose output .TP .B \fB\-h\fR .br
0