29 files modified
2 files added
| New file |
| | |
| | | #!/usr/bin/env bash |
| | | # The contents of this file are subject to the terms of the Common Development and |
| | | # Distribution License (the License). You may not use this file except in compliance with the |
| | | # License. |
| | | # |
| | | # You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the |
| | | # specific language governing permission and limitations under the License. |
| | | # |
| | | # When distributing Covered Software, include this CDDL Header Notice in each file and include |
| | | # the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL |
| | | # Header, with the fields enclosed by brackets [] replaced by your own identifying |
| | | # information: "Portions copyright [year] [name of copyright owner]". |
| | | # |
| | | # Copyright 2026 3A Systems, LLC. |
| | | |
| | | step_status=$1 |
| | | container_id=$2 |
| | | |
| | | if stop_output=$(docker stop "$container_id" 2>&1); then |
| | | exit "$step_status" |
| | | else |
| | | stop_status=$? |
| | | fi |
| | | |
| | | # Docker may have already removed a container started with --rm. |
| | | if running=$(docker ps --quiet --filter "id=$container_id") && [[ -z "$running" ]]; then |
| | | exit "$step_status" |
| | | fi |
| | | |
| | | printf '%s\n' "$stop_output" >&2 |
| | | if (( step_status == 0 )); then |
| | | exit "$stop_status" |
| | | fi |
| | | exit "$step_status" |
| | |
| | | - name: Set Integration Test Environment |
| | | id: failsafe |
| | | if: runner.os == 'Linux' |
| | | run: | |
| | | echo "MAVEN_PROFILE_FLAG=-P precommit" >> $GITHUB_OUTPUT |
| | | run: | |
| | | echo "MAVEN_PROFILE_FLAG=-P precommit" >> "$GITHUB_OUTPUT" |
| | | |
| | | - name: Setup WiX (.NET tool) for MSI |
| | | # Only the java 11 job's MSI is consumed downstream (test-msi*, deploy.yml); without |
| | |
| | | - name: Test LDAP in Cassandra |
| | | if: runner.os == 'Linux' |
| | | run: | |
| | | docker run --rm -it -d -p 9042:9042 --name cassandra cassandra |
| | | container_id=$(docker run --rm -it -d -p 9042:9042 --name cassandra cassandra) |
| | | trap 'bash .github/scripts/stop-test-container.sh "$?" "$container_id" || exit "$?"' EXIT |
| | | timeout 5m bash -c 'until docker logs cassandra | grep -q "Created default superuser role"; do sleep 5; done' |
| | | export OPENDJ_JAVA_ARGS="-server -Xmx512m -Ddatastax-java-driver.basic.contact-points.0=localhost:9042 -Ddatastax-java-driver.basic.load-balancing-policy.local-datacenter=datacenter1" |
| | | opendj-server-legacy/target/package/opendj/setup -h localhost -p 1389 --ldapsPort 1636 --adminConnectorPort 4444 --enableStartTLS --generateSelfSignedCertificate --rootUserDN "cn=Directory Manager" --rootUserPassword password --cli --acceptLicense --no-prompt |
| | |
| | | - name: Test LDAP in Postgres |
| | | if: runner.os == 'Linux' |
| | | run: | |
| | | docker run --rm -it -d -p 5432:5432 -e POSTGRES_DB=database_name -e POSTGRES_PASSWORD=password --name postgres postgres |
| | | container_id=$(docker run --rm -it -d -p 5432:5432 -e POSTGRES_DB=database_name -e POSTGRES_PASSWORD=password --name postgres postgres) |
| | | trap 'bash .github/scripts/stop-test-container.sh "$?" "$container_id" || exit "$?"' EXIT |
| | | timeout 5m bash -c 'until docker logs postgres | grep -q "database system is ready to accept connections"; do sleep 5; done' |
| | | export OPENDJ_JAVA_ARGS="-server -Xmx512m" |
| | | opendj-server-legacy/target/package/opendj/setup -h localhost -p 1389 --ldapsPort 1636 --adminConnectorPort 4444 --enableStartTLS --generateSelfSignedCertificate --rootUserDN "cn=Directory Manager" --rootUserPassword password --cli --acceptLicense --no-prompt |
| | |
| | | anchor:chap-ldap-sdk[] |
| | | endif::[] |
| | | |
| | | This example uses the OpenDJ LDAP SDK {opendj-sdk-example-version} to check which LDAP versions a server supports. |
| | | These examples use the OpenDJ LDAP SDK {opendj-sdk-example-version} to read server capabilities, manage directory entries over LDAPS, and reuse connections. |
| | | |
| | | [#ldap-sdk-maven] |
| | | === Add the SDK to a Maven Project |
| | | |
| | | Use Java 11 or later and Maven 3. Save this `pom.xml`. The `opendj-grizzly` dependency brings in the `opendj-core` SDK and provides its LDAP network transport. |
| | | Use Java 11 or later and Maven 3. In xref:../getting-started/first-steps.adoc#getting-started-first-directory[Your First Directory], complete *Set Up and Start the Server*. Keep the evaluation server running and retain `quickstart-password.txt` for the Java exercises. If you already completed the Quickstart cleanup, restart the server with `opendj/bin/start-ds` from `opendj-quickstart` and re-create `quickstart-password.txt` there with the same Directory Manager password and permissions readable only by you. |
| | | |
| | | From the directory containing `opendj-quickstart`, create the Java project next to it. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | mkdir -p ldap-client/src/main/java |
| | | cd ldap-client |
| | | ---- |
| | | |
| | | Save this `pom.xml` in `ldap-client`. The `opendj-grizzly` dependency brings in the `opendj-core` SDK and provides its LDAP network transport. |
| | | |
| | | [source,xml,subs="+attributes"] |
| | | ---- |
| | |
| | | [#ldap-sdk-search] |
| | | === Read the Root DSE |
| | | |
| | | Start the evaluation server from xref:../getting-started/first-steps.adoc#getting-started-first-directory[Your First Directory]. The example reads the root DSE, an entry with public server information, from its LDAP listener on port 1389. |
| | | The example reads the root DSE, an entry with server information, anonymously from the evaluation server's LDAP listener on port 1389. |
| | | |
| | | Save this class as `src/main/java/ReadCapabilities.java`. |
| | | |
| | |
| | | RootDSE rootDse = RootDSE.readRootDSE(connection); |
| | | var versions = rootDse.getSupportedLDAPVersions(); |
| | | System.out.println("LDAPv3 supported = " + versions.contains(3)); |
| | | System.out.println("Naming contexts = " + rootDse.getNamingContexts()); |
| | | } |
| | | } |
| | | } |
| | |
| | | mvn -q compile exec:java -Dexec.mainClass=ReadCapabilities |
| | | ---- |
| | | |
| | | The program prints `LDAPv3 supported = true`. The link:{opendj-sdk-javadoc}/ldap/RootDSE.html[`RootDSE`] class also exposes naming contexts, supported controls, and extended operations. |
| | | The program prints `LDAPv3 supported = true`. Check that the naming contexts include `dc=example,dc=com`. The link:{opendj-sdk-javadoc}/ldap/RootDSE.html[`RootDSE`] class also exposes supported controls and extended operations. |
| | | |
| | | For an existing directory, obtain the server hostname, listener port and TLS mode, trusted CA certificates, service-account DN, and permitted search base from its administrator. Use `getNamingContexts()` on a verified connection to identify the directory suffixes visible to your account. Choose a search base within the suffix that contains the application data. |
| | | |
| | | * The *Bind DN* identifies the account whose credentials the client presents. |
| | | * The *base DN* is the starting point of a search, such as `ou=People,dc=example,dc=com`. |
| | | * The *entry DN* identifies a particular record, such as `uid=alice,ou=People,dc=example,dc=com`. Its first component, `uid=alice`, is the relative distinguished name (RDN). |
| | | |
| | | [#ldap-sdk-entry-operations] |
| | | === Add, Search, Modify, and Delete Entries |
| | | |
| | | Use the running evaluation server with the `dc=example,dc=com` base entry and the `quickstart-password.txt` file created during setup. From `ldap-client`, export the evaluation server's public certificate and import it into a new client truststore. The password in these commands protects the example truststore, which contains only the public certificate. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | server=../opendj-quickstart/opendj |
| | | keytool -exportcert -rfc -alias server-cert \ |
| | | -keystore "$server/config/keystore" -storepass:file "$server/config/keystore.pin" \ |
| | | -file ldap-server.pem && |
| | | keytool -importcert -noprompt -alias server-cert -file ldap-server.pem \ |
| | | -keystore ldap-trust.p12 -storetype PKCS12 -storepass changeit |
| | | ---- |
| | | |
| | | Save the TLS setup as `src/main/java/LocalLdaps.java`. The examples use it to open verified LDAPS connections to the evaluation server. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import org.forgerock.opendj.ldap.LDAPConnectionFactory; |
| | | import org.forgerock.opendj.ldap.SSLContextBuilder; |
| | | import org.forgerock.opendj.ldap.TrustManagers; |
| | | import org.forgerock.util.Options; |
| | | |
| | | final class LocalLdaps { |
| | | static final String HOST = "localhost"; |
| | | static final int PORT = 1636; |
| | | |
| | | static Options options() throws Exception { |
| | | var trust = TrustManagers.checkUsingTrustStore( |
| | | "ldap-trust.p12", "changeit".toCharArray(), "PKCS12"); |
| | | var trustManager = TrustManagers.checkValidityDates(TrustManagers.checkHostName(HOST, trust)); |
| | | var sslContext = new SSLContextBuilder().setTrustManager(trustManager).getSSLContext(); |
| | | return Options.defaultOptions().set(LDAPConnectionFactory.SSL_CONTEXT, sslContext); |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Save the following class as `src/main/java/ManageEntries.java`. The Directory Manager account is for this evaluation server. In an application, use an account with access to the entries and operations it needs. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Path; |
| | | import java.util.Arrays; |
| | | import java.util.UUID; |
| | | |
| | | import org.forgerock.opendj.ldap.Connection; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.Filter; |
| | | import org.forgerock.opendj.ldap.LDAPConnectionFactory; |
| | | import org.forgerock.opendj.ldap.ModificationType; |
| | | import org.forgerock.opendj.ldap.SearchScope; |
| | | import org.forgerock.opendj.ldap.requests.Requests; |
| | | import org.forgerock.opendj.ldif.ConnectionEntryReader; |
| | | |
| | | public final class ManageEntries { |
| | | public static void main(String[] args) throws Exception { |
| | | try (LDAPConnectionFactory factory = |
| | | new LDAPConnectionFactory(LocalLdaps.HOST, LocalLdaps.PORT, LocalLdaps.options()); |
| | | Connection connection = factory.getConnection()) { |
| | | char[] password = Files.readAllLines(Path.of("../opendj-quickstart/quickstart-password.txt")) |
| | | .get(0).toCharArray(); |
| | | try { |
| | | connection.bind("cn=Directory Manager", password); |
| | | } finally { |
| | | Arrays.fill(password, '\0'); |
| | | } |
| | | |
| | | var identity = connection.extendedRequest(Requests.newWhoAmIExtendedRequest()); |
| | | System.out.println("Authorization identity = " + identity.getAuthorizationID()); |
| | | manageEntries(connection); |
| | | } |
| | | } |
| | | |
| | | private static void manageEntries(Connection connection) throws Exception { |
| | | String ou = "SdkExample-" + UUID.randomUUID(); |
| | | String branch = "ou=" + ou + ",dc=example,dc=com"; |
| | | String person = "uid=sdk-alice," + branch; |
| | | String newRdn = "uid=sdk-alice-renamed"; |
| | | String renamed = newRdn + "," + branch; |
| | | String originalMail = "sdk-alice@example.com"; |
| | | String updatedMail = "sdk-alice-renamed@example.com"; |
| | | |
| | | connection.add(Requests.newAddRequest(branch) |
| | | .addAttribute("objectClass", "top", "organizationalUnit") |
| | | .addAttribute("ou", ou)); |
| | | System.out.println("Created sample branch " + branch); |
| | | connection.add(Requests.newAddRequest(person) |
| | | .addAttribute("objectClass", "top", "inetOrgPerson") |
| | | .addAttribute("uid", "sdk-alice") |
| | | .addAttribute("cn", "Alice Jensen") |
| | | .addAttribute("sn", "Jensen") |
| | | .addAttribute("mail", originalMail)); |
| | | |
| | | var search = Requests.newSearchRequest(DN.valueOf(branch), SearchScope.SINGLE_LEVEL, |
| | | Filter.equality("uid", "sdk-alice"), "cn", "mail"); |
| | | try (ConnectionEntryReader reader = connection.search(search)) { |
| | | while (reader.hasNext()) { |
| | | if (reader.isEntry()) { |
| | | var entry = reader.readEntry(); |
| | | System.out.println("Found " + entry.getName() + " (" + entry.parseAttribute("cn").asString() |
| | | + ", " + entry.parseAttribute("mail").asString() + ")"); |
| | | } else { |
| | | System.out.println("Search reference " + reader.readReference().getURIs()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | connection.modify(Requests.newModifyRequest(person) |
| | | .addModification(ModificationType.ADD, "description", "LDAP SDK example") |
| | | .addModification(ModificationType.REPLACE, "mail", updatedMail) |
| | | .addModification(ModificationType.DELETE, "description", "LDAP SDK example")); |
| | | System.out.println("Updated mail matches = " + connection.compare(person, "mail", updatedMail).matched()); |
| | | System.out.println("Original mail matches = " + connection.compare(person, "mail", originalMail).matched()); |
| | | |
| | | connection.modifyDN(Requests.newModifyDNRequest(person, newRdn).setDeleteOldRDN(true)); |
| | | System.out.println("Renamed to " + connection.readEntry(renamed, "mail").getName()); |
| | | |
| | | connection.delete(renamed); |
| | | connection.delete(branch); |
| | | System.out.println("Removed sample branch " + branch); |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Run the program from `ldap-client`. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | mvn -q compile exec:java -Dexec.mainClass=ManageEntries |
| | | ---- |
| | | |
| | | Expect one search match, `true` for the updated email comparison, and `false` for the original email comparison. The program prints the renamed DN and removes its sample branch. If an operation fails after creation, use the printed branch DN to locate any remaining sample entries. Delete children before deleting their parent. |
| | | |
| | | * *Bind and extended operations.* Bind sets the connection's authentication state. The Who Am I? extended operation reports the resulting authorization identity. Use `RootDSE.getSupportedExtendedOperations()` to discover optional operations before sending them. To use StartTLS instead of LDAPS, keep the same trust settings, set `LDAPConnectionFactory.SSL_USE_STARTTLS` to `true`, and connect to the LDAP port with StartTLS enabled. The factory negotiates TLS before returning the connection. |
| | | * *Search.* `readEntry` performs a base-object lookup by DN. `SINGLE_LEVEL` searches the immediate children, `WHOLE_SUBTREE` includes the base and all descendants, and `SUBORDINATES` searches all descendants where the server supports that scope. Use `Filter.equality` or `Filter.format` for application-supplied assertion values. The example reports continuation references. Follow them only to servers your application trusts. See xref:chap-ldap-operations.adoc#search-ldap[Searching the Directory] for the equivalent command-line operations. |
| | | * *Modify and Modify DN.* Add and delete can change individual values of a multivalued attribute, and replace sets its new value list. Use `ModificationType.INCREMENT` on supported servers for integer increments. To move an entry, set the destination parent with `setNewSuperior` on the Modify DN request. Set `setDeleteOldRDN(true)` to remove the old naming value during a rename. |
| | | * *Compare and delete.* `CompareResult.matched()` distinguishes the normal LDAP results `COMPARE_TRUE` and `COMPARE_FALSE`. A standard Delete removes a leaf entry. Use `deleteSubtree` only when the application intends to remove the whole branch and the server supports the subtree delete control. |
| | | * *Abandon and Unbind.* Closing a `ConnectionEntryReader` cancels its search if it is still active. For other asynchronous operations, cancel the returned `LdapPromise` to request abandonment where supported. The Cancel extended operation is a separate request with its own result. Closing a direct LDAP connection sends Unbind when possible and releases the connection. |
| | | * *Errors.* SDK methods report LDAP failures through `LdapException`. Use `e.getResult().getResultCode()` to distinguish conditions such as `ENTRY_ALREADY_EXISTS`, `NO_SUCH_OBJECT`, and `INSUFFICIENT_ACCESS_RIGHTS`. Use `e.getLocalizedMessage()` for messages presented to users. A search may yield entries before reporting a final LDAP error, such as `SIZE_LIMIT_EXCEEDED`. |
| | | |
| | | [#ldap-sdk-choose-search] |
| | | === Choose a Search Method |
| | | |
| | | [cols="2,3",options="header"] |
| | | |=== |
| | | |Method |When to use it |
| | | |
| | | |`readEntry(dn, attributes)` |
| | | |You already know the entry DN. A missing entry raises `EntryNotFoundException`. |
| | | |
| | | |`searchSingleEntry(request)` |
| | | |You expect exactly one match, such as a unique login. Zero matches produce `CLIENT_SIDE_NO_RESULTS_RETURNED`. Multiple or otherwise unexpected results raise `MultipleEntriesFoundException`. |
| | | |
| | | |`search(request)` |
| | | |You expect zero or more matches. Consume entries and continuation references through `ConnectionEntryReader`. A successful search can return zero entries. Consume the complete result to detect a final LDAP error. |
| | | |=== |
| | | |
| | | Build filters with methods such as `Filter.equality("uid", login)` so that characters in the supplied value are treated literally. Request the attributes the application uses. For an optional single value, call `entry.parseAttribute("mail").asString("")` to supply a default. For a multivalued attribute, call `entry.parseAttribute("mail").asSetOfString()` and handle an empty set. A missing value can also reflect the account's read permissions. |
| | | |
| | | [#ldap-sdk-search-and-bind] |
| | | === Find a User and Verify a Password |
| | | |
| | | Use a service account to find the user's DN, then bind as the user on a separate connection. Both connections use verified TLS. Keep the service account's privileges limited to the search and attributes required by the application. |
| | | |
| | | On the evaluation server, create a reader account and two sample records. Run the following Bash block from `ldap-client` after creating the LDAPS truststore. It uses `openssl` to generate temporary passwords and grants the reader search and read access to the sample users' login and object class. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | sdk_admin() { |
| | | local tool=$1 |
| | | shift |
| | | "../opendj-quickstart/opendj/bin/$tool" --hostname localhost --port 1636 --useSSL \ |
| | | --trustStorePath ldap-trust.p12 --trustStorePassword changeit \ |
| | | --bindDN 'cn=Directory Manager' \ |
| | | --bindPasswordFile ../opendj-quickstart/quickstart-password.txt "$@" |
| | | } |
| | | |
| | | SDK_READER_PASSWORD=$(openssl rand -hex 16) && |
| | | SDK_USER_PASSWORD=$(openssl rand -hex 16) && |
| | | export SDK_READER_PASSWORD SDK_USER_PASSWORD && |
| | | sdk_admin ldapmodify --defaultAdd <<LDIF |
| | | dn: uid=sdk-reader,dc=example,dc=com |
| | | objectClass: inetOrgPerson |
| | | uid: sdk-reader |
| | | cn: SDK Reader |
| | | sn: Reader |
| | | userPassword: ${SDK_READER_PASSWORD} |
| | | |
| | | dn: ou=SdkUsers,dc=example,dc=com |
| | | objectClass: organizationalUnit |
| | | ou: SdkUsers |
| | | aci: (targetattr = "uid || objectClass")(version 3.0; acl "Search SDK users"; allow (read,search) userdn = "ldap:///uid=sdk-reader,dc=example,dc=com";) |
| | | |
| | | dn: uid=sdk-alice,ou=SdkUsers,dc=example,dc=com |
| | | objectClass: inetOrgPerson |
| | | uid: sdk-alice |
| | | cn: SDK Alice |
| | | sn: Alice |
| | | userPassword: ${SDK_USER_PASSWORD} |
| | | |
| | | dn: uid=sdk-bob,ou=SdkUsers,dc=example,dc=com |
| | | objectClass: inetOrgPerson |
| | | uid: sdk-bob |
| | | cn: SDK Bob |
| | | sn: Bob |
| | | LDIF |
| | | ---- |
| | | |
| | | Save this class as `src/main/java/SearchAndBind.java`. It uses `AUTHN_BIND_REQUEST` to configure the service pool. The user's password travels only on the separate LDAPS connection. Reject an empty password before calling Bind. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import java.util.Arrays; |
| | | |
| | | import org.forgerock.opendj.ldap.Connection; |
| | | import org.forgerock.opendj.ldap.ConnectionPool; |
| | | import org.forgerock.opendj.ldap.Connections; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.EntryNotFoundException; |
| | | import org.forgerock.opendj.ldap.Filter; |
| | | import org.forgerock.opendj.ldap.LDAPConnectionFactory; |
| | | import org.forgerock.opendj.ldap.LdapException; |
| | | import org.forgerock.opendj.ldap.MultipleEntriesFoundException; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.forgerock.opendj.ldap.SearchScope; |
| | | import org.forgerock.opendj.ldap.requests.Requests; |
| | | |
| | | public final class SearchAndBind { |
| | | static final DN USERS_BASE = DN.valueOf("ou=SdkUsers,dc=example,dc=com"); |
| | | private static final String READER_DN = "uid=sdk-reader,dc=example,dc=com"; |
| | | |
| | | public static void main(String[] args) throws Exception { |
| | | if (args.length != 1 || args[0].isBlank()) { |
| | | throw new IllegalArgumentException("Pass one login, for example sdk-alice"); |
| | | } |
| | | |
| | | DN userDN; |
| | | try (ConnectionPool pool = newReaderPool(); |
| | | Connection reader = pool.getConnection()) { |
| | | var request = Requests.newSearchRequest(USERS_BASE, SearchScope.SINGLE_LEVEL, |
| | | Filter.equality("uid", args[0]), "uid"); |
| | | userDN = reader.searchSingleEntry(request).getName(); |
| | | } catch (EntryNotFoundException e) { |
| | | if (e.getResult().getResultCode() != ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED) { |
| | | throw e; |
| | | } |
| | | System.out.println("No matching user"); |
| | | return; |
| | | } catch (MultipleEntriesFoundException e) { |
| | | System.out.println("Could not select one user. Check for duplicate matches, referrals, or search limits."); |
| | | return; |
| | | } |
| | | |
| | | char[] password = requirePassword("SDK_USER_PASSWORD"); |
| | | try (LDAPConnectionFactory factory = |
| | | new LDAPConnectionFactory(LocalLdaps.HOST, LocalLdaps.PORT, LocalLdaps.options()); |
| | | Connection connection = factory.getConnection()) { |
| | | connection.bind(userDN.toString(), password); |
| | | System.out.println("Authenticated " + userDN); |
| | | } catch (LdapException e) { |
| | | if (e.getResult().getResultCode() != ResultCode.INVALID_CREDENTIALS) { |
| | | throw e; |
| | | } |
| | | System.out.println("Invalid credentials"); |
| | | } finally { |
| | | Arrays.fill(password, '\0'); |
| | | } |
| | | } |
| | | |
| | | static ConnectionPool newReaderPool() throws Exception { |
| | | char[] password = requirePassword("SDK_READER_PASSWORD"); |
| | | try { |
| | | var bind = Requests.newSimpleBindRequest(READER_DN, password); |
| | | var options = LocalLdaps.options().set(LDAPConnectionFactory.AUTHN_BIND_REQUEST, bind); |
| | | return Connections.newFixedConnectionPool( |
| | | new LDAPConnectionFactory(LocalLdaps.HOST, LocalLdaps.PORT, options), 4); |
| | | } finally { |
| | | Arrays.fill(password, '\0'); |
| | | } |
| | | } |
| | | |
| | | private static char[] requirePassword(String variable) { |
| | | String value = System.getenv(variable); |
| | | if (value == null || value.isEmpty()) { |
| | | throw new IllegalArgumentException("Set " + variable + " to a nonempty password"); |
| | | } |
| | | return value.toCharArray(); |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Run these commands to try a successful login, an absent login, and a wrong password. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | mvn -q compile exec:java -Dexec.mainClass=SearchAndBind -Dexec.args=sdk-alice |
| | | mvn -q compile exec:java -Dexec.mainClass=SearchAndBind -Dexec.args=sdk-unknown |
| | | SDK_USER_PASSWORD=wrong-test-password \ |
| | | mvn -q compile exec:java -Dexec.mainClass=SearchAndBind -Dexec.args=sdk-alice |
| | | ---- |
| | | |
| | | To try the duplicate case on the evaluation server, temporarily add a second entry under `ou=SdkUsers` with a different DN and the same `uid: sdk-alice`. Repeat the lookup and remove the second entry. |
| | | |
| | | The example prints separate outcomes for the exercise. In an application, give the same sign-in response for an unknown login and incorrect credentials. Keep a single service pool for the application's lifetime, and supply its password from the application's secret store. Closing a borrowed service connection returns it to the pool. |
| | | |
| | | [#ldap-sdk-paged-search] |
| | | === Read Search Results Page by Page |
| | | |
| | | Use the sample users and lookup pool from the preceding exercise. Save this class as `src/main/java/PagedSearch.java`. It requests one result per page to demonstrate more than one request. It holds a single connection while sending each response cookie with the next request. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import org.forgerock.opendj.ldap.ByteString; |
| | | import org.forgerock.opendj.ldap.Connection; |
| | | import org.forgerock.opendj.ldap.ConnectionPool; |
| | | import org.forgerock.opendj.ldap.DecodeOptions; |
| | | import org.forgerock.opendj.ldap.Filter; |
| | | import org.forgerock.opendj.ldap.RootDSE; |
| | | import org.forgerock.opendj.ldap.SearchScope; |
| | | import org.forgerock.opendj.ldap.controls.SimplePagedResultsControl; |
| | | import org.forgerock.opendj.ldap.requests.Requests; |
| | | import org.forgerock.opendj.ldif.ConnectionEntryReader; |
| | | |
| | | public final class PagedSearch { |
| | | public static void main(String[] args) throws Exception { |
| | | try (ConnectionPool pool = SearchAndBind.newReaderPool(); |
| | | Connection connection = pool.getConnection()) { |
| | | if (!RootDSE.readRootDSE(connection).getSupportedControls().contains(SimplePagedResultsControl.OID)) { |
| | | throw new IllegalStateException("The server does not advertise paged results"); |
| | | } |
| | | |
| | | ByteString cookie = ByteString.empty(); |
| | | do { |
| | | var request = Requests.newSearchRequest(SearchAndBind.USERS_BASE, SearchScope.SINGLE_LEVEL, |
| | | Filter.equality("objectClass", "inetOrgPerson"), "uid").setTimeLimit(5); |
| | | request.addControl(SimplePagedResultsControl.newControl(true, 1, cookie)); |
| | | try (ConnectionEntryReader reader = connection.search(request)) { |
| | | while (reader.hasNext()) { |
| | | if (reader.isEntry()) { |
| | | System.out.println(reader.readEntry().getName()); |
| | | } else { |
| | | System.out.println("Search reference " + reader.readReference().getURIs()); |
| | | } |
| | | } |
| | | var response = reader.readResult().getControl(SimplePagedResultsControl.DECODER, new DecodeOptions()); |
| | | if (response == null) { |
| | | throw new IllegalStateException("Missing paged results response control"); |
| | | } |
| | | cookie = response.getCookie(); |
| | | } |
| | | } while (cookie.length() != 0); |
| | | } |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Run `mvn -q compile exec:java -Dexec.mainClass=PagedSearch`. Expect the two sample user DNs. An empty cookie ends the search. Keep the base, scope, filter, and requested attributes the same across pages. Page size controls the number requested per page. `setSizeLimit` and `setTimeLimit` request server-side limits on entries and elapsed search time in seconds. A final `SIZE_LIMIT_EXCEEDED` or `TIME_LIMIT_EXCEEDED` means you have partial results. |
| | | |
| | | [#ldap-sdk-async-search] |
| | | === Run an Asynchronous Search |
| | | |
| | | Save this class as `src/main/java/FindUserAsync.java`. The promise starts the search after the pool supplies a connection. Its completion handler returns the connection to the pool on success or failure. The command-line program waits for the result with `getOrThrow()`. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import org.forgerock.opendj.ldap.ConnectionPool; |
| | | import org.forgerock.opendj.ldap.Filter; |
| | | import org.forgerock.opendj.ldap.SearchScope; |
| | | import org.forgerock.opendj.ldap.requests.Requests; |
| | | |
| | | public final class FindUserAsync { |
| | | public static void main(String[] args) throws Exception { |
| | | var request = Requests.newSearchRequest(SearchAndBind.USERS_BASE, SearchScope.SINGLE_LEVEL, |
| | | Filter.equality("uid", "sdk-alice"), "uid"); |
| | | try (ConnectionPool pool = SearchAndBind.newReaderPool()) { |
| | | var lookup = pool.getConnectionAsync().thenAsync(connection -> { |
| | | try { |
| | | return connection.searchSingleEntryAsync(request).thenFinally(connection::close); |
| | | } catch (RuntimeException e) { |
| | | connection.close(); |
| | | throw e; |
| | | } |
| | | }); |
| | | System.out.println(lookup.getOrThrow().getName()); |
| | | } |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Run `mvn -q compile exec:java -Dexec.mainClass=FindUserAsync`. Expect the DN of `sdk-alice`. Use the link:{opendj-sdk-examples}/SearchAsync.java[`SearchAsync.java`] example for asynchronous searches that deliver multiple entries. |
| | | |
| | | Remove the sample entries before the evaluation server cleanup. Run this in the shell where you defined `sdk_admin`. |
| | | |
| | | [source,bash] |
| | | ---- |
| | | printf '%s\n' \ |
| | | 'uid=sdk-alice,ou=SdkUsers,dc=example,dc=com' \ |
| | | 'uid=sdk-bob,ou=SdkUsers,dc=example,dc=com' \ |
| | | 'ou=SdkUsers,dc=example,dc=com' \ |
| | | 'uid=sdk-reader,dc=example,dc=com' | |
| | | sdk_admin ldapdelete |
| | | unset SDK_READER_PASSWORD SDK_USER_PASSWORD |
| | | ---- |
| | | |
| | | [#ldap-sdk-troubleshooting] |
| | | === Diagnose Client Errors |
| | | |
| | | Log the operation, the result code from `LdapException.getResult()`, and the exception cause when applicable. Keep passwords out of logs. For an application-facing error, show a message appropriate for the failed operation. |
| | | |
| | | [cols="2,3",options="header"] |
| | | |=== |
| | | |Symptom |First check |
| | | |
| | | |Connection refused or `CLIENT_SIDE_CONNECT_ERROR` |
| | | |Check that the server is running and that the host, port, and LDAP or LDAPS listener match. Run the Root DSE example against the evaluation listener to verify connectivity. |
| | | |
| | | |TLS handshake or certificate error |
| | | |Check the exception cause for an untrusted certificate chain or a hostname mismatch. Verify that the LDAPS or StartTLS mode matches the listener and that the truststore contains the appropriate CA or the evaluation server's certificate. |
| | | |
| | | |`INVALID_CREDENTIALS` |
| | | |Check the Bind DN, its password and the account state. Use a separate Bind to distinguish the service-account login from the user's login. |
| | | |
| | | |`INSUFFICIENT_ACCESS_RIGHTS` |
| | | |Check the account reported by Who Am I? and the access control rules for the requested entry, operation, and attributes. |
| | | |
| | | |`NO_SUCH_OBJECT` or zero results |
| | | |Check the search base or target DN first. If the base exists, check the search scope, filter and the account's search visibility. |
| | | |
| | | |`CLIENT_SIDE_TIMEOUT` or a server search limit |
| | | |Check whether the timeout is on the client or the server. Narrow the scope or filter, and verify that the application handles partial search results before retrying. |
| | | |=== |
| | | |
| | | If a write times out after transmission, read the entry before deciding whether to retry. A sequence of separate LDAP requests can leave changes from earlier requests in place. For integration tests, create a dedicated branch, assert the returned entry and error codes, and remove the branch after each test. Use a test OpenDJ instance for checks that depend on TLS, access controls, or server-side search limits. |
| | | |
| | | [#ldap-sdk-connection-settings] |
| | | === LDAP Connection Settings |
| | | |
| | | Pass the server host, port, and an `Options` instance to link:{opendj-sdk-javadoc}/ldap/LDAPConnectionFactory.html[`LDAPConnectionFactory`]. Set each option with `Options.defaultOptions().set(option, value)`. A pool uses the options of its underlying factory when it opens physical connections. The defaults below apply to OpenDJ LDAP SDK {opendj-sdk-example-version}. |
| | | |
| | | [cols="2,1,4",options="header"] |
| | | |=== |
| | | |Option on `LDAPConnectionFactory` |Default |Effect |
| | | |
| | | |`CONNECT_TIMEOUT` |
| | | |10 seconds |
| | | |Maximum time to establish a physical connection, including TCP, TLS negotiation, an initial bind, and an initial heartbeat when applicable. Use zero to leave the TCP connection timeout to the operating system and disable the SDK's overall connection deadline. The JVM property `org.forgerock.opendj.io.connectTimeout` sets the default in milliseconds. |
| | | |
| | | |`REQUEST_TIMEOUT` |
| | | |0 (disabled) |
| | | |Client timeout for an LDAP operation waiting for a response. Grizzly reports `CLIENT_SIDE_TIMEOUT` when it expires. The JVM property `org.forgerock.opendj.io.requestTimeout` sets the default in milliseconds. Its legacy fallback is `org.forgerock.opendj.io.timeout`. |
| | | |
| | | |`AUTHN_BIND_REQUEST` |
| | | |Unset |
| | | |A `BindRequest` sent when opening each physical connection, after TLS negotiation if configured. A failed bind causes connection acquisition to fail. |
| | | |
| | | |`SSL_CONTEXT` |
| | | |Unset |
| | | |Supply an `SSLContext` to enable TLS and configure certificate validation. An unset context uses plaintext LDAP. |
| | | |
| | | |`SSL_USE_STARTTLS` |
| | | |`false` |
| | | |With an SSL context, `false` uses LDAPS and `true` upgrades an LDAP connection using StartTLS. |
| | | |
| | | |`SSL_ENABLED_PROTOCOLS` |
| | | |Empty list |
| | | |List of TLS protocol names enabled on secure connections. An empty list uses the SSL engine's enabled protocols. |
| | | |
| | | |`SSL_ENABLED_CIPHER_SUITES` |
| | | |Empty list |
| | | |List of TLS cipher suites enabled on secure connections. An empty list uses the SSL engine's enabled suites. |
| | | |
| | | |`HEARTBEAT_ENABLED` |
| | | |`false` |
| | | |Enable periodic LDAP searches on idle connections to detect an unresponsive server. |
| | | |
| | | |`HEARTBEAT_INTERVAL` |
| | | |10 seconds |
| | | |Interval between heartbeat checks. Use a positive duration when heartbeats are enabled. |
| | | |
| | | |`HEARTBEAT_TIMEOUT` |
| | | |3 seconds |
| | | |Response deadline for a periodic heartbeat. A shorter enabled request timeout can expire first. Use a positive duration when heartbeats are enabled. |
| | | |
| | | |`HEARTBEAT_SEARCH_REQUEST` |
| | | |Root DSE base search |
| | | |Override the heartbeat `SearchRequest`. The default uses the filter `(objectClass=*)` and requests no attributes (`1.1`). |
| | | |
| | | |`HEARTBEAT_SCHEDULER` |
| | | |Shared SDK scheduler |
| | | |Supply a `ScheduledExecutorService` for heartbeat work and the SDK's connection setup deadline. |
| | | |=== |
| | | |
| | | Timeout and interval options use `org.forgerock.util.time.Duration`. Set the time unit when creating the duration, for example `Duration.duration(5, TimeUnit.SECONDS)`. |
| | | |
| | | The connection factory also accepts these inherited options and the Grizzly transport option. |
| | | |
| | | [cols="2,2,4",options="header"] |
| | | |=== |
| | | |Option |Default |Effect |
| | | |
| | | |`TCP_NO_DELAY` |
| | | |`true` |
| | | |Set the `TCP_NODELAY` socket option. The JVM property `org.forgerock.opendj.io.tcpNoDelay` sets the default. |
| | | |
| | | |`SO_KEEPALIVE` |
| | | |`true` |
| | | |Enable operating-system TCP keepalives through `SO_KEEPALIVE`. The JVM property `org.forgerock.opendj.io.keepAlive` sets the default. |
| | | |
| | | |`SO_REUSE_ADDRESS` |
| | | |`true` |
| | | |Set the `SO_REUSEADDR` socket option. The JVM property `org.forgerock.opendj.io.reuseAddress` sets the default. |
| | | |
| | | |`SO_LINGER_IN_SECONDS` |
| | | |`-1` (disabled) |
| | | |Configure how long socket close may wait for queued data. Use a negative value to disable `SO_LINGER`. The JVM property `org.forgerock.opendj.io.linger` sets the default in seconds. |
| | | |
| | | |`LDAP_DECODE_OPTIONS` |
| | | |Default schema and factories |
| | | |Supply `DecodeOptions` to select the schema resolver, entry factory, and attribute factory for decoding LDAP messages. |
| | | |
| | | |`TRANSPORT_PROVIDER` |
| | | |First discovered provider |
| | | |Select the `TransportProvider` by name. The `opendj-grizzly` dependency provides `Grizzly`. |
| | | |
| | | |`TRANSPORT_PROVIDER_CLASS_LOADER` |
| | | |Class loader of `TransportProvider` |
| | | |Specify the class loader used by `ServiceLoader` to find the transport provider. |
| | | |
| | | |`GrizzlyLDAPConnectionFactory.GRIZZLY_TRANSPORT` |
| | | |Shared SDK transport |
| | | |Supply a Grizzly `TCPNIOTransport` to configure the underlying network transport. |
| | | |=== |
| | | |
| | | [#ldap-sdk-connection-pools] |
| | | === Reuse LDAP Connections |
| | | |
| | | Create a link:{opendj-sdk-javadoc}/ldap/ConnectionPool.html[`ConnectionPool`] once for a workload with the same server and authentication settings. Borrow a connection for each unit of work and close it with try-with-resources to return it to the pool. Complete any asynchronous requests and close any search readers before returning the connection. Close the pool at application shutdown to release its connections and its underlying factory. |
| | | |
| | | Choose the pool configuration according to how long the application should keep idle connections and how many concurrent borrowers it can support. All three options create connections on demand. |
| | | |
| | | [cols="1,2,3",options="header"] |
| | | |=== |
| | | |Pool |Factory method in `Connections` |Behavior |
| | | |
| | | |Fixed |
| | | |`newFixedConnectionPool(factory, 8)` |
| | | |Keeps up to eight connections. Established idle connections stay in the pool until they become invalid or the pool closes. |
| | | |
| | | |Bounded cached |
| | | |`newCachedConnectionPool(factory, 2, 8, 60, TimeUnit.SECONDS)` |
| | | |Grows to at most eight connections. Idle connections above the core size of two become eligible for eviction after 60 seconds. The core size does not pre-open connections. |
| | | |
| | | |Default cached |
| | | |`newCachedConnectionPool(factory)` |
| | | |Uses a core size of zero, an effectively unbounded maximum, and a 60-second idle timeout. A burst can create as many connections as the workload demands within resource limits. |
| | | |=== |
| | | |
| | | [#ldap-sdk-pool-settings] |
| | | ==== Connection Pool Settings |
| | | |
| | | Set pool parameters when calling the factory methods in `Connections`. The cached defaults below apply to `newCachedConnectionPool(factory)`. |
| | | |
| | | [cols="1,2,4",options="header"] |
| | | |=== |
| | | |Argument |Default |Effect |
| | | |
| | | |`factory` |
| | | |Required |
| | | |Underlying `ConnectionFactory` used to open physical connections. |
| | | |
| | | |`poolSize` |
| | | |Required for a fixed pool |
| | | |Positive size passed to `newFixedConnectionPool`. The fixed pool uses this value as both its core and maximum size. |
| | | |
| | | |`corePoolSize` |
| | | |`0` |
| | | |Minimum number of established connections to retain during idle eviction. Use a value between zero and `maximumPoolSize`. A core size of zero lets an idle pool shrink to zero when eviction is enabled. |
| | | |
| | | |`maximumPoolSize` |
| | | |`Integer.MAX_VALUE` |
| | | |Positive limit on the number of physical connections in the cached pool. Use an explicit maximum to bound load on the directory server. |
| | | |
| | | |`idleTimeout` |
| | | |60 seconds |
| | | |Time an idle connection above the core size must wait before it is eligible for eviction. Cleanup runs periodically. Zero disables idle eviction. |
| | | |
| | | |`unit` |
| | | |`TimeUnit.SECONDS` |
| | | |Unit of the `idleTimeout` argument. Supply a unit whenever the timeout is positive. |
| | | |
| | | |`scheduler` |
| | | |Shared SDK scheduler |
| | | |The six-argument cached-pool overload accepts a `ScheduledExecutorService` for idle cleanup. The caller manages the lifetime of a supplied executor. |
| | | |=== |
| | | |
| | | When a bounded pool is at maximum size and all its connections are in use, `getConnection()` waits for an available connection. That wait can exceed `CONNECT_TIMEOUT`, which applies to physical connection setup. Use `getConnectionAsync()` to acquire a connection without blocking the caller. Set the application concurrency limit and release connections promptly to control pool contention. |
| | | |
| | | Save this class as `src/main/java/ReadWithPool.java`. It borrows and returns a connection twice from the same pool, using the anonymous Root DSE read from the first example. |
| | | |
| | | [source,java] |
| | | ---- |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | import org.forgerock.opendj.ldap.Connection; |
| | | import org.forgerock.opendj.ldap.ConnectionPool; |
| | | import org.forgerock.opendj.ldap.Connections; |
| | | import org.forgerock.opendj.ldap.LDAPConnectionFactory; |
| | | import org.forgerock.opendj.ldap.RootDSE; |
| | | |
| | | public final class ReadWithPool { |
| | | public static void main(String[] args) throws Exception { |
| | | LDAPConnectionFactory factory = new LDAPConnectionFactory("localhost", 1389); |
| | | try (ConnectionPool pool = Connections.newCachedConnectionPool(factory, 2, 8, 60, TimeUnit.SECONDS)) { |
| | | for (int i = 0; i < 2; i++) { |
| | | try (Connection connection = pool.getConnection()) { |
| | | var versions = RootDSE.readRootDSE(connection).getSupportedLDAPVersions(); |
| | | System.out.println("LDAPv3 supported = " + versions.contains(3)); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | ---- |
| | | |
| | | Run `mvn -q compile exec:java -Dexec.mainClass=ReadWithPool`. Both reads should print `LDAPv3 supported = true`. To try the other configurations, replace the pool construction with either alternative from the table. |
| | | |
| | | For an authenticated pool, configure TLS on the factory and set `LDAPConnectionFactory.AUTHN_BIND_REQUEST` to a bind request for the service account. The factory binds each physical connection before it is available to the pool. Perform per-user binds on separate, unpooled connections, because a bind changes the identity of the underlying connection. |
| | | |
| | | [#ldap-sdk-load-balancing] |
| | | ==== Load Balancing Across Servers |
| | | |
| | | Use a pool per server to set its connection limits and reuse connections. Combine the pools with a load-balancing factory from link:{opendj-sdk-javadoc}/ldap/Connections.html[`Connections`] to choose which server or partition receives work. |
| | | |
| | | [cols="1,2,3",options="header"] |
| | | |=== |
| | | |Strategy |Factory method in `Connections` |Routing behavior |
| | | |
| | | |Round robin (RR) |
| | | |`newRoundRobinLoadBalancer(pools, options)` |
| | | |Selects a server when the caller borrows a connection. Rotates through the available servers to distribute connection acquisitions across equivalent replicas. |
| | | |
| | | |Failover |
| | | |`newFailoverLoadBalancer(pools, options)` |
| | | |Selects the first available server in the configured order when the caller borrows a connection. Put the preferred server or site first. |
| | | |
| | | |Least requests |
| | | |`newLeastRequestsLoadBalancer(pools, options)` |
| | | |Routes each LDAP request to the replica with the fewest in-flight requests tracked by this factory. Use it when concurrent requests have different durations. |
| | | |
| | | |DN affinity |
| | | |`newAffinityRequestLoadBalancer(pools, options)` |
| | | |Hashes the target DN to prefer the same replica for requests to that DN. Use the same replica order in each client that needs the same routing. |
| | | |
| | | |Partitioned distribution |
| | | |`newFixedSizeDistributionLoadBalancer(partitionBaseDN, partitions, options)` |
| | | |Uses a `ConsistentHashMap` to map each subtree immediately below the partition base DN to a partition. A search that spans partitions can fan out according to its base DN and scope. |
| | | |=== |
| | | |
| | | Least-connections routing uses open connection counts and requires an external load balancer that supports that policy. |
| | | |
| | | With round robin or failover, operations on the borrowed connection use the same server. The request-level strategies borrow a connection for each operation and can send successive operations to different servers. Use a single server connection for operations that depend on the same LDAP session. |
| | | |
| | | Searches that span multiple partitions reject simple paged results, server-side sort, and virtual list view controls. Modify DN requests that move an entry across partition boundaries are rejected. |
| | | |
| | | The following `Connections` options apply to the four replica strategies. |
| | | |
| | | [cols="2,2,4",options="header"] |
| | | |=== |
| | | |Option |Default |Effect |
| | | |
| | | |`LOAD_BALANCER_MONITORING_INTERVAL` |
| | | |1 second |
| | | |Delay between connection attempts to factories marked offline. |
| | | |
| | | |`LOAD_BALANCER_EVENT_LISTENER` |
| | | |`LoadBalancerEventListener.LOG_EVENTS` |
| | | |Receive online and offline events. The default listener logs state changes. |
| | | |
| | | |`LOAD_BALANCER_SCHEDULER` |
| | | |Shared SDK scheduler |
| | | |Supply a `ScheduledExecutorService` to run reconnect checks. |
| | | |=== |
| | | |
| | | Close the load-balancing factory at shutdown to close its underlying pools. If a write loses its connection before a response arrives, check the directory state before retrying the write. |
| | | |
| | | The link:{opendj-sdk-examples}/Proxy.java[`Proxy.java`] example combines pools with the `least-requests`, `fail-over`, `affinity`, and `distribution` modes. |
| | | |
| | | [#ldap-sdk-next-steps] |
| | | === Use the SDK in an Application |
| | | === OpenDJ LDAP SDK Examples |
| | | |
| | | * For simple authentication, call `Connection.bind` after connecting over LDAPS or StartTLS. Configure link:{opendj-sdk-javadoc}/ldap/LDAPConnectionFactory.html[`LDAPConnectionFactory`] with `SSL_CONTEXT` and a trust configuration that validates the server certificate and identity. Set `SSL_USE_STARTTLS` to `true` to negotiate TLS on an LDAP listener. See `getTrustOptions()` in link:{opendj-sdk-examples}/SimpleAuth.java[`SimpleAuth.java`] for certificate and hostname verification. |
| | | * For SASL PLAIN, use link:{opendj-sdk-examples}/SASLAuth.java[`SASLAuth.java`] to see how to construct the bind request. Its StartTLS setup uses `TrustManagers.trustAll()` for local testing. Use the verified TLS setup above when sending credentials from an application. |
| | | * Use `Connection.search` to read multiple entries. Set a specific base DN, scope and filter, and request the attributes you need. See xref:chap-ldap-operations.adoc#search-ldap[Searching the Directory] for equivalent command-line examples and link:{opendj-sdk-examples}/Search.java[`Search`] for an SDK example that handles entries and continuation references. Follow referrals only to servers your application trusts. Use `Connection.compare` to compare an attribute value and check the LDAP result code for the outcome. |
| | | * Use a connection factory or a pool for repeated operations. Close connections when finished with them and close the factory at application shutdown. Use separate connections for binds as different users. For concurrent operations, see link:{opendj-sdk-examples}/SearchAsync.java[`SearchAsync`] and link:{opendj-sdk-examples}/ModifyAsync.java[`ModifyAsync`]. SDK methods report LDAP failures through `LdapException`, whose result carries the LDAP result code and diagnostic details. |
| | | * Use link:{opendj-sdk-javadoc}/ldap/requests/Requests.html[`Requests`] to construct add, modify, modify DN, delete, and extended operation requests. See link:{opendj-sdk-examples}/Modify.java[`Modify`], link:{opendj-sdk-examples}/UpdateGroup.java[`UpdateGroup`], and link:{opendj-sdk-examples}/ExtendedOperations.java[`ExtendedOperations`]. For request controls, check `supportedControl` before depending on a control and see link:{opendj-sdk-examples}/Controls.java[`Controls`] and link:{opendj-sdk-examples}/UseGenericControl.java[`UseGenericControl`]. |
| | | * For schema discovery, read `subschemaSubentry` or use the link:{opendj-sdk-examples}/ReadSchema.java[`ReadSchema`] example. For files in LDAP Data Interchange Format (LDIF), use the link:{opendj-sdk-javadoc}/ldif/package-summary.html[`org.forgerock.opendj.ldif`] readers and writers. Use an entry reader for entries and a change record reader for LDIF files that describe updates. |
| | | * The SDK uses localized messages. Handle errors by result code and use `getLocalizedMessage()` for messages presented to users. |
| | | * A proxy can reuse connections and distribute them among servers with link:{opendj-sdk-javadoc}/ldap/Connections.html[`Connections`]. For listener and request handler examples, see link:{opendj-sdk-examples}/Proxy.java[`Proxy`] and link:{opendj-sdk-examples}/RewriterProxy.java[`RewriterProxy`]. |
| | | The `opendj-ldap-sdk-examples` module contains the following examples for OpenDJ {opendj-sdk-example-version}. Check the class documentation for command-line arguments, sample entries, and required server capabilities. Some of these examples use plaintext LDAP, fixed test credentials, or `TrustManagers.trustAll()`. Use the verified TLS configuration from xref:chap-ldap-sdk.adoc#ldap-sdk-entry-operations[Add, Search, Modify, and Delete Entries] when adapting these clients for application credentials. |
| | | |
| | | [cols="2,3",options="header"] |
| | | |=== |
| | | |Example |What it demonstrates |
| | | |
| | | |link:{opendj-sdk-examples}/GetInfo.java[`GetInfo`] |
| | | |Reads the root DSE anonymously and prints supported controls, supported extended operations, or operational attributes as LDIF. |
| | | |
| | | |link:{opendj-sdk-examples}/SimpleAuth.java[`SimpleAuth`], link:{opendj-sdk-examples}/SimpleAuthAsync.java[`SimpleAuthAsync`] |
| | | |Perform a simple bind, with options for LDAPS or StartTLS. The asynchronous version chains connection acquisition and bind. |
| | | |
| | | |link:{opendj-sdk-examples}/SASLAuth.java[`SASLAuth`] |
| | | |Constructs a SASL PLAIN bind request and sends it over StartTLS. |
| | | |
| | | |link:{opendj-sdk-examples}/SearchBind.java[`SearchBind`], link:{opendj-sdk-examples}/SearchBindAsync.java[`SearchBindAsync`] |
| | | |Prompt for an email address and password, find the user's DN by email, and bind as that user. The asynchronous version chains search and bind. |
| | | |
| | | |link:{opendj-sdk-examples}/Search.java[`Search`] |
| | | |Searches by base DN, scope, filter, and requested attributes. Writes entries as LDIF and reports continuation references. |
| | | |
| | | |link:{opendj-sdk-examples}/SearchAsync.java[`SearchAsync`] |
| | | |Processes entries and references with an asynchronous result handler and demonstrates the Cancel extended operation. |
| | | |
| | | |link:{opendj-sdk-examples}/ShortLife.java[`ShortLife`], link:{opendj-sdk-examples}/ShortLifeAsync.java[`ShortLifeAsync`] |
| | | |Create, modify, rename, and delete a temporary entry using synchronous calls or a chain of asynchronous requests. |
| | | |
| | | |link:{opendj-sdk-examples}/Modify.java[`Modify`] |
| | | |Applies a stream of LDIF change records from a file or standard input using `ConnectionChangeRecordWriter`. |
| | | |
| | | |link:{opendj-sdk-examples}/ModifyAsync.java[`ModifyAsync`] |
| | | |Builds one Modify request from LDIF read from a file or standard input and submits it with `modifyAsync`. |
| | | |
| | | |link:{opendj-sdk-examples}/UpdateGroup.java[`UpdateGroup`], link:{opendj-sdk-examples}/UpdateGroupAsync.java[`UpdateGroupAsync`] |
| | | |Add or remove a member of a static `groupOfNames` group. Use the Permissive Modify control when supported and otherwise compare membership before changing it. |
| | | |
| | | |link:{opendj-sdk-examples}/ParseAttributes.java[`ParseAttributes`] |
| | | |Updates and reads a test entry, then converts attribute values to Java types such as integers, DNs, and timestamps. |
| | | |
| | | |link:{opendj-sdk-examples}/ReadSchema.java[`ReadSchema`] |
| | | |Reads the server schema and prints a summary and any parsing warnings. |
| | | |
| | | |link:{opendj-sdk-examples}/UseSchema.java[`UseSchema`], link:{opendj-sdk-examples}/UseSchemaAsync.java[`UseSchemaAsync`] |
| | | |Validate an entry from standard input against the server schema before adding it, using synchronous or asynchronous calls. |
| | | |
| | | |link:{opendj-sdk-examples}/Controls.java[`Controls`] |
| | | |Discovers controls through the root DSE and demonstrates paged results, server-side sort, pre-read and post-read, and other controls. Select the method for the control you want to try. |
| | | |
| | | |link:{opendj-sdk-examples}/UseGenericControl.java[`UseGenericControl`] |
| | | |Encodes a Pre-Read request control with ASN.1, attaches it to a Modify request, and decodes the response to retrieve the old attribute value. |
| | | |
| | | |link:{opendj-sdk-examples}/ExtendedOperations.java[`ExtendedOperations`] |
| | | |Discovers supported extended operations and demonstrates Who Am I? and Password Modify. |
| | | |
| | | |link:{opendj-sdk-examples}/GetADChangeNotifications.java[`GetADChangeNotifications`] |
| | | |Watches a naming context for changes using the Microsoft Active Directory notification control. |
| | | |
| | | |link:{opendj-sdk-examples}/PasswordResetForAD.java[`PasswordResetForAD`] |
| | | |Changes or resets an Active Directory password by modifying `unicodePwd` over LDAPS. |
| | | |
| | | |link:{opendj-sdk-examples}/Server.java[`Server`] |
| | | |Exposes entries from an LDIF file through an LDAP listener with an in-memory backend and optional LDAPS. |
| | | |
| | | |link:{opendj-sdk-examples}/Proxy.java[`Proxy`] |
| | | |Starts an LDAP proxy that combines per-server connection pools with least-requests, failover, affinity, or distribution routing. |
| | | |
| | | |link:{opendj-sdk-examples}/ProxyBackend.java[`ProxyBackend`] |
| | | |Implements the per-client request handler used by `Proxy`. It forwards operations with proxied authorization and uses a separate connection factory for binds. |
| | | |
| | | |link:{opendj-sdk-examples}/RewriterProxy.java[`RewriterProxy`] |
| | | |Starts a proxy that rewrites a fixed DN suffix and attribute name between clients and an upstream server. |
| | | |=== |
| | | |
| | | link:{opendj-sdk-examples}/ExampleUtils.java[`ExampleUtils`] provides shared command-line port parsing. link:{opendj-sdk-examples}/package-info.java[`package-info.java`] describes the package. |
| | |
| | | * |
| | | * Copyright 2010 Sun Microsystems, Inc. |
| | | * Portions copyright 2011-2016 ForgeRock AS. |
| | | * Portions copyright 2025-2026 3A Systems, LLC. |
| | | * Portions Copyright 2025-2026 3A Systems, LLC. |
| | | */ |
| | | package org.forgerock.opendj.grizzly; |
| | | |
| | |
| | | import java.util.Collection; |
| | | import java.util.HashSet; |
| | | import java.util.Set; |
| | | import java.util.concurrent.ExecutionException; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.TimeoutException; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | |
| | | import org.forgerock.util.Function; |
| | | import org.forgerock.util.Option; |
| | | import org.forgerock.util.Options; |
| | | import org.glassfish.grizzly.EmptyCompletionHandler; |
| | | import org.glassfish.grizzly.filterchain.FilterChain; |
| | | import org.glassfish.grizzly.impl.FutureImpl; |
| | | import org.glassfish.grizzly.nio.SelectorHandler; |
| | | import org.glassfish.grizzly.nio.SelectorRunner; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOBindingHandler; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOConnection; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOServerConnection; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOTransport; |
| | | import org.glassfish.grizzly.utils.Futures; |
| | | |
| | | import com.forgerock.opendj.util.ReferenceCountedObject; |
| | | import com.forgerock.reactive.ReactiveHandler; |
| | |
| | | |
| | | @Override |
| | | public void close() { |
| | | if (isClosed.compareAndSet(false, true)) { |
| | | for (TCPNIOConnection serverConnection : serverConnections) { |
| | | try { |
| | | close(false); |
| | | } catch (IOException e) { |
| | | logger.warn(LocalizableMessage.raw("Exception occurred while closing listener"), e); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Closes the listener and waits for the accept sockets to be released. |
| | | * Call this from outside the transport's selector threads. If the transport was supplied by the caller, the |
| | | * caller still owns it and can drain existing connections. |
| | | * |
| | | * @throws IOException |
| | | * If an accept socket could not be closed and deregistered. |
| | | */ |
| | | public void closeAndAwaitPortRelease() throws IOException { |
| | | close(true); |
| | | } |
| | | |
| | | private void close(boolean awaitPortRelease) throws IOException { |
| | | if (!isClosed.compareAndSet(false, true)) { |
| | | return; |
| | | } |
| | | IOException failure = null; |
| | | try { |
| | | for (TCPNIOServerConnection serverConnection : serverConnections) { |
| | | try { |
| | | serverConnection.close().get(5, TimeUnit.SECONDS); |
| | | } catch (final Exception e) { |
| | | // TODO: I18N |
| | | logger.warn(LocalizableMessage.raw("Exception occurred while closing listener", e)); |
| | | closeServerConnection(serverConnection, awaitPortRelease); |
| | | } catch (IOException e) { |
| | | if (failure == null) { |
| | | failure = e; |
| | | } else { |
| | | failure.addSuppressed(e); |
| | | } |
| | | } |
| | | } |
| | | } finally { |
| | | transport.release(); |
| | | } |
| | | if (failure != null) { |
| | | throw failure; |
| | | } |
| | | } |
| | | |
| | | private void closeServerConnection(TCPNIOServerConnection connection, boolean awaitPortRelease) throws IOException { |
| | | try { |
| | | final SelectorRunner runner = connection.getSelectorRunner(); |
| | | if (awaitPortRelease && runner != null) { |
| | | final FutureImpl<SelectorHandler.Task> released = Futures.createSafeFuture(); |
| | | final SelectorHandler selectorHandler = transport.get().getSelectorHandler(); |
| | | // A closed NIO channel can still own the socket until the selector processes its cancelled key. |
| | | // Enqueue the check from the owning thread so it runs after the next selection cycle. |
| | | selectorHandler.enque(runner, () -> { |
| | | connection.closeSilently(); |
| | | selectorHandler.enque(runner, () -> { |
| | | if (connection.getChannel().isOpen() || connection.getChannel().isRegistered()) { |
| | | throw new IOException("Listening socket is still registered: " + connection.getLocalAddress()); |
| | | } |
| | | return true; |
| | | }, Futures.toCompletionHandler(released)); |
| | | return true; |
| | | }, new EmptyCompletionHandler<SelectorHandler.Task>() { |
| | | @Override |
| | | public void failed(Throwable cause) { |
| | | released.failure(cause); |
| | | } |
| | | }); |
| | | released.get(5, TimeUnit.SECONDS); |
| | | } else { |
| | | connection.close().get(5, TimeUnit.SECONDS); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | throw new IOException("Interrupted while closing listener", e); |
| | | } catch (ExecutionException | TimeoutException e) { |
| | | throw new IOException("Could not close listener", e); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | |
| | | --> |
| | | <profile> |
| | | <id>precommit</id> |
| | | <properties> |
| | | <opendj.precommit.forkCount>4</opendj.precommit.forkCount> |
| | | </properties> |
| | | <build><finalName>${project.groupId}.${project.artifactId}</finalName> |
| | | <plugins> |
| | | |
| | |
| | | <systemPropertyVariables> |
| | | <org.opends.server.BuildRoot>${basedir}</org.opends.server.BuildRoot> |
| | | <org.opends.server.BuildDir>${project.build.directory}</org.opends.server.BuildDir> |
| | | <org.opends.test.forkCount>${opendj.precommit.forkCount}</org.opends.test.forkCount> |
| | | <org.opends.test.replicationDbImpl>LOG</org.opends.test.replicationDbImpl> |
| | | <org.opends.server.snmp.opendmk>${opendmk.lib.dir}</org.opends.server.snmp.opendmk> |
| | | <org.opends.server.CleanupDirectories>true</org.opends.server.CleanupDirectories> |
| | |
| | | <environmentVariables> |
| | | <JAVA_TOOL_OPTIONS>-Dorg.bouncycastle.native.cpu_variant=java</JAVA_TOOL_OPTIONS> |
| | | </environmentVariables> |
| | | <argLine>@{argLine}</argLine> |
| | | <!-- Failsafe substitutes the fork number in each JVM command line. --> |
| | | <argLine>@{argLine} -Dorg.opends.test.forkNumber=${surefire.forkNumber}</argLine> |
| | | <reuseForks>false</reuseForks> |
| | | <forkCount>1</forkCount> |
| | | <forkCount>${opendj.precommit.forkCount}</forkCount> |
| | | <parallel>none</parallel> |
| | | <runOrder>alphabetical</runOrder> |
| | | <!-- |
| | |
| | | import java.util.Set; |
| | | import java.util.SortedSet; |
| | | import java.util.TreeSet; |
| | | import java.util.concurrent.CompletableFuture; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.concurrent.CopyOnWriteArrayList; |
| | | import java.util.concurrent.ExecutionException; |
| | | import java.util.concurrent.ScheduledExecutorService; |
| | | import java.util.concurrent.ScheduledThreadPoolExecutor; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.TimeoutException; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | |
| | | import javax.net.ssl.KeyManager; |
| | |
| | | /** SSL instance name used in context creation. */ |
| | | private static final String SSL_CONTEXT_INSTANCE_NAME = "TLS"; |
| | | |
| | | private LDAPListener listener; |
| | | private GrizzlyLDAPListener listener; |
| | | |
| | | /** |
| | | * The transport serving the connections of this connection handler only. It is started with the listener, and |
| | |
| | | private volatile boolean shutdownRequested; |
| | | |
| | | /** |
| | | * The server this handler was initialized for. The listener stops on the thread of the handler, up to a second |
| | | * after the handler is finalized: after an in-core restart the current server instance is by then the next one, |
| | | * so only this one tells whether the server of the connections is shutting down. |
| | | * The server this handler was initialized for. The transport may still be draining after an in-core restart, |
| | | * so only this instance tells whether the server of its connections is shutting down. |
| | | */ |
| | | private DirectoryServer server; |
| | | |
| | |
| | | private final QueueingStrategy queueingStrategy; |
| | | |
| | | /** |
| | | * The condition variable that will be used by the start method to wait for the socket port to be opened and ready |
| | | * to process requests before returning. |
| | | * Coordinates the listener's startup and wakes the listener thread on shutdown. |
| | | */ |
| | | private final Object waitListen = new Object(); |
| | | |
| | |
| | | */ |
| | | private boolean listenAttempted; |
| | | |
| | | /** Allows finalization to wait for the listen socket to close before an in-core restart. */ |
| | | private final CompletableFuture<Void> listenerClosed = new CompletableFuture<>(); |
| | | |
| | | /** The friendly name of this connection handler. */ |
| | | private String friendlyName; |
| | | |
| | |
| | | |
| | | @Override |
| | | public void finalizeConnectionHandler(LocalizableMessage finalizeReason) { |
| | | shutdownRequested = true; |
| | | finalizeConnectionHandler(finalizeReason, true); |
| | | } |
| | | |
| | | @Override |
| | | public void finalizeConnectionHandlerForConfigurationChange(LocalizableMessage finalizeReason) { |
| | | // The listener's selector may be waiting for the worker applying this change to make queue space. |
| | | finalizeConnectionHandler(finalizeReason, false); |
| | | } |
| | | |
| | | private void finalizeConnectionHandler(LocalizableMessage finalizeReason, boolean awaitPortRelease) { |
| | | processServerShutdown(finalizeReason); |
| | | currentConfig.removeLDAPChangeListener(this); |
| | | |
| | | if (connMonitor != null) { |
| | |
| | | r.run(); // Flush active queue. |
| | | r.run(); // Flush pending queue. |
| | | } |
| | | |
| | | if (awaitPortRelease && getState() != Thread.State.NEW && Thread.currentThread() != this) { |
| | | try { |
| | | listenerClosed.get(LISTEN_TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | } catch (InterruptedException e) { |
| | | Thread.currentThread().interrupt(); |
| | | throw new IllegalStateException("Interrupted while closing listener " + handlerName, e); |
| | | } catch (ExecutionException | TimeoutException e) { |
| | | throw new IllegalStateException("Could not close listener " + handlerName, e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | |
| | | |
| | | @Override |
| | | public void processServerShutdown(LocalizableMessage reason) { |
| | | shutdownRequested = true; |
| | | synchronized (waitListen) { |
| | | shutdownRequested = true; |
| | | waitListen.notifyAll(); |
| | | } |
| | | } |
| | | |
| | | void stopListener() { |
| | | try { |
| | | closeListener(); |
| | | } catch (IOException e) { |
| | | logger.traceException(e); |
| | | logger.warn(LocalizableMessage.raw("Could not close listener %s", handlerName)); |
| | | } finally { |
| | | drainTransport(); |
| | | } |
| | | } |
| | | |
| | | private void closeListener() throws IOException { |
| | | if (listener != null) { |
| | | listener.close(); |
| | | final GrizzlyLDAPListener closing = listener; |
| | | listener = null; |
| | | closing.closeAndAwaitPortRelease(); |
| | | logger.info(NOTE_CONNHANDLER_STOPPED_LISTENING, handlerName); |
| | | } |
| | | } |
| | | |
| | | private void drainTransport() { |
| | | if (transport != null) { |
| | | final TransportDrain drain = new TransportDrain(transport, transportConnections, transportOpenConnections); |
| | | transport = null; |
| | |
| | | transport = newTransport(openConnections); |
| | | transportConnections = accepted; |
| | | transportOpenConnections = openConnections; |
| | | listener = new LDAPListener( |
| | | listener = new GrizzlyLDAPListener( |
| | | listenAddresses, |
| | | new Function<LDAPClientContext, |
| | | ReactiveHandler<LDAPClientContext, LdapRequestEnvelope, Stream<Response>>, |
| | |
| | | .set(LDAPListener.REQUEST_MAX_SIZE_IN_BYTES, (int) currentConfig.getMaxRequestSize()) |
| | | // Set by the listener on every accepted connection, over the values of the transport. |
| | | .set(LDAPListener.SO_KEEPALIVE, useTCPKeepAlive) |
| | | .set(LDAPListener.TCP_NO_DELAY, useTCPNoDelay) |
| | | .set(GrizzlyLDAPListener.GRIZZLY_TRANSPORT, transport)); |
| | | .set(LDAPListener.TCP_NO_DELAY, useTCPNoDelay), transport); |
| | | logger.info(NOTE_CONNHANDLER_STARTED_LISTENING, handlerName); |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | StaticUtils.sleep(1000); |
| | | waitForListenerChange(); |
| | | continue; |
| | | } |
| | | |
| | | if (listener != null) { |
| | | // If already listening, then sleep for a bit and check again. |
| | | StaticUtils.sleep(1000); |
| | | waitForListenerChange(); |
| | | continue; |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | // Initiate shutdown |
| | | stopListener(); |
| | | try { |
| | | closeListener(); |
| | | listenerClosed.complete(null); |
| | | } catch (Exception e) { |
| | | listenerClosed.completeExceptionally(e); |
| | | logger.warn(LocalizableMessage.raw("Could not close listener %s", handlerName), e); |
| | | } finally { |
| | | drainTransport(); |
| | | } |
| | | } |
| | | |
| | | private void waitForListenerChange() { |
| | | synchronized (waitListen) { |
| | | if (!shutdownRequested) { |
| | | try { |
| | | waitListen.wait(1000); |
| | | } catch (InterruptedException e) { |
| | | // Recheck the listener state. |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | private LDAPClientConnection2 canAccept(LDAPClientContext clientContext) throws LdapException { |
| | |
| | | public abstract void finalizeConnectionHandler( |
| | | LocalizableMessage finalizeReason); |
| | | |
| | | /** |
| | | * Stops this handler after its configuration is disabled or deleted. |
| | | * This can run on a work queue worker. Handlers whose listeners depend on |
| | | * the work queue can initiate closure asynchronously. |
| | | * |
| | | * @param finalizeReason |
| | | * The reason that this connection handler should be finalized. |
| | | */ |
| | | public void finalizeConnectionHandlerForConfigurationChange(LocalizableMessage finalizeReason) |
| | | { |
| | | finalizeConnectionHandler(finalizeReason); |
| | | } |
| | | |
| | | |
| | | |
| | | /** |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.api; |
| | | |
| | |
| | | |
| | | |
| | | /** |
| | | * Allows a queue to reject new submissions and release submitters waiting for capacity |
| | | * before the server shuts down its connection handlers. Queued and active operations |
| | | * can continue until {@link #finalizeWorkQueue(LocalizableMessage)}. |
| | | */ |
| | | public void stopAcceptingOperations() |
| | | { |
| | | // By default, admission stops when the queue is finalized. |
| | | } |
| | | |
| | | |
| | | |
| | | /** |
| | | * Performs any necessary finalization for this work queue, |
| | | * including ensuring that all active operations are interrupted or |
| | | * will be allowed to complete, and that all pending operations will |
| | |
| | | .deregisterConnectionHandler(connectionHandler); |
| | | connectionHandlers.remove(dn); |
| | | |
| | | connectionHandler.finalizeConnectionHandler( |
| | | connectionHandler.finalizeConnectionHandlerForConfigurationChange( |
| | | INFO_CONNHANDLER_CLOSED_BY_DISABLE.get()); |
| | | } |
| | | } |
| | |
| | | DirectoryServer.deregisterConnectionHandler(connectionHandler); |
| | | connectionHandlers.remove(dn); |
| | | |
| | | connectionHandler.finalizeConnectionHandler( |
| | | connectionHandler.finalizeConnectionHandlerForConfigurationChange( |
| | | INFO_CONNHANDLER_CLOSED_BY_DELETE.get()); |
| | | } |
| | | |
| | |
| | | ServerShutdownMonitor shutdownMonitor = new ServerShutdownMonitor(); |
| | | shutdownMonitor.start(); |
| | | |
| | | // Release connection-handler threads that are waiting for queue space. |
| | | if (directoryServer.workQueue != null) |
| | | { |
| | | directoryServer.workQueue.stopAcceptingOperations(); |
| | | } |
| | | |
| | | // Shut down the connection handlers. |
| | | for (ConnectionHandler<?> handler : directoryServer.connectionHandlers) |
| | | { |
| | |
| | | * |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.extensions; |
| | | |
| | | import static org.opends.messages.ConfigMessages.*; |
| | | import static org.opends.messages.CoreMessages.*; |
| | | |
| | | import java.util.ArrayDeque; |
| | | import java.util.ArrayList; |
| | | import java.util.Deque; |
| | | import java.util.List; |
| | | import java.util.concurrent.LinkedBlockingQueue; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | import java.util.concurrent.atomic.AtomicLong; |
| | | import java.util.concurrent.locks.ReentrantReadWriteLock; |
| | | import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; |
| | | import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; |
| | | import java.util.concurrent.locks.Condition; |
| | | import java.util.concurrent.locks.ReentrantLock; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.i18n.slf4j.LocalizedLogger; |
| | |
| | | */ |
| | | private boolean killThreads; |
| | | |
| | | /** Indicates whether submissions have been closed before queue finalization. Guarded by queueLock. */ |
| | | private boolean submissionsClosed; |
| | | |
| | | /** Indicates whether the Directory Server is shutting down. */ |
| | | private boolean shutdownRequested; |
| | | private volatile boolean shutdownRequested; |
| | | |
| | | /** The thread number used for the last worker thread that was created. */ |
| | | private int lastThreadNumber; |
| | |
| | | * The number of worker threads that should be active (or will be shortly if a |
| | | * configuration change has not been completely applied). |
| | | */ |
| | | private int numWorkerThreads; |
| | | private volatile int numWorkerThreads; |
| | | |
| | | /** |
| | | * The queue overflow policy: true indicates that operations will be blocked |
| | |
| | | */ |
| | | private final boolean isBlocking = true; |
| | | |
| | | /** The queue that will be used to actually hold the pending operations. */ |
| | | private LinkedBlockingQueue<Operation> opQueue; |
| | | |
| | | /** The lock used to provide threadsafe access for the queue, used for non-config changes. */ |
| | | private final ReadLock queueReadLock; |
| | | |
| | | /** The lock used to provide threadsafe access for the queue, used for config changes. */ |
| | | private final WriteLock queueWriteLock; |
| | | { |
| | | ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); |
| | | queueReadLock = lock.readLock(); |
| | | queueWriteLock = lock.writeLock(); |
| | | } |
| | | /** Guards the queue, capacity, and worker pool. Condition waits release the lock. */ |
| | | private final ReentrantLock queueLock = new ReentrantLock(); |
| | | private final Condition workAvailable = queueLock.newCondition(); |
| | | private final Condition spaceAvailable = queueLock.newCondition(); |
| | | private final Deque<Operation> opQueue = new ArrayDeque<>(); |
| | | |
| | | /** |
| | | * Creates a new instance of this work queue. All initialization should be |
| | |
| | | public void initializeWorkQueue(TraditionalWorkQueueCfg configuration) |
| | | throws ConfigException, InitializationException |
| | | { |
| | | queueWriteLock.lock(); |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | submissionsClosed = false; |
| | | shutdownRequested = false; |
| | | killThreads = false; |
| | | opsSubmitted = new AtomicLong(0); |
| | |
| | | computeNumWorkerThreads(configuration.getNumWorkerThreads()); |
| | | maxCapacity = configuration.getMaxWorkQueueCapacity(); |
| | | |
| | | // Create the actual work queue. |
| | | if (maxCapacity > 0) |
| | | { |
| | | opQueue = new LinkedBlockingQueue<>(maxCapacity); |
| | | } |
| | | else |
| | | { |
| | | // This will never be the case, since the configuration definition |
| | | // ensures that the capacity is always finite. |
| | | opQueue = new LinkedBlockingQueue<>(); |
| | | } |
| | | opQueue.clear(); |
| | | |
| | | // Create the set of worker threads that should be used to service the |
| | | // work queue. |
| | |
| | | workerThreads.add(t); |
| | | } |
| | | |
| | | // Create and register a monitor provider for the work queue. |
| | | try |
| | | { |
| | | TraditionalWorkQueueMonitor monitor = new TraditionalWorkQueueMonitor( |
| | | this); |
| | | monitor.initializeMonitorProvider(null); |
| | | DirectoryServer.registerMonitorProvider(monitor); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | logger.error(ERR_CONFIG_WORK_QUEUE_CANNOT_CREATE_MONITOR, TraditionalWorkQueueMonitor.class, e); |
| | | } |
| | | registerQueueMonitor(); |
| | | } |
| | | finally |
| | | { |
| | | queueWriteLock.unlock(); |
| | | queueLock.unlock(); |
| | | } |
| | | } |
| | | |
| | | void registerQueueMonitor() |
| | | { |
| | | try |
| | | { |
| | | TraditionalWorkQueueMonitor monitor = new TraditionalWorkQueueMonitor(this); |
| | | monitor.initializeMonitorProvider(null); |
| | | DirectoryServer.registerMonitorProvider(monitor); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | logger.error(ERR_CONFIG_WORK_QUEUE_CANNOT_CREATE_MONITOR, TraditionalWorkQueue.class, e); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void stopAcceptingOperations() |
| | | { |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | submissionsClosed = true; |
| | | spaceAvailable.signalAll(); |
| | | } |
| | | finally |
| | | { |
| | | queueLock.unlock(); |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void finalizeWorkQueue(LocalizableMessage reason) |
| | | { |
| | | queueWriteLock.lock(); |
| | | List<Operation> pendingOperations; |
| | | List<TraditionalWorkerThread> workers; |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | shutdownRequested = true; |
| | | pendingOperations = new ArrayList<>(opQueue); |
| | | opQueue.clear(); |
| | | workers = new ArrayList<>(workerThreads); |
| | | workAvailable.signalAll(); |
| | | spaceAvailable.signalAll(); |
| | | } |
| | | finally |
| | | { |
| | | queueWriteLock.unlock(); |
| | | queueLock.unlock(); |
| | | } |
| | | |
| | | // From now on no more operations can be enqueued or dequeued. |
| | | |
| | | // Send responses to any operations in the pending queue to indicate that |
| | | // they won't be processed because the server is shutting down. |
| | | CancelRequest cancelRequest = new CancelRequest(true, reason); |
| | | ArrayList<Operation> pendingOperations = new ArrayList<>(); |
| | | opQueue.drainTo(pendingOperations); |
| | | for (Operation o : pendingOperations) |
| | | for (Operation operation : pendingOperations) |
| | | { |
| | | try |
| | | { |
| | | // The operation has no chance of responding to the cancel |
| | | // request so avoid waiting for a cancel response. |
| | | if (o.getCancelResult() == null) |
| | | { |
| | | o.abort(cancelRequest); |
| | | } |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | logger.warn(WARN_QUEUE_UNABLE_TO_CANCEL, o, e); |
| | | } |
| | | abortPendingOperation(operation, cancelRequest); |
| | | } |
| | | |
| | | // Notify all the worker threads of the shutdown. |
| | | for (TraditionalWorkerThread t : workerThreads) |
| | | for (TraditionalWorkerThread worker : workers) |
| | | { |
| | | try |
| | | { |
| | | t.shutDown(); |
| | | worker.shutDown(); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | logger.warn(WARN_QUEUE_UNABLE_TO_NOTIFY_THREAD, t.getName(), e); |
| | | logger.warn(WARN_QUEUE_UNABLE_TO_NOTIFY_THREAD, worker.getName(), e); |
| | | } |
| | | } |
| | | } |
| | | |
| | | void abortPendingOperation(Operation operation, CancelRequest cancelRequest) |
| | | { |
| | | try |
| | | { |
| | | // Pending operations have no worker to answer a cancel request. |
| | | if (operation.getCancelResult() == null) |
| | | { |
| | | operation.abort(cancelRequest); |
| | | } |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | logger.warn(WARN_QUEUE_UNABLE_TO_CANCEL, operation, e); |
| | | } |
| | | finally |
| | | { |
| | | operationDone(); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Indicates whether this work queue has received a request to shut down. |
| | | * |
| | |
| | | */ |
| | | public boolean shutdownRequested() |
| | | { |
| | | queueReadLock.lock(); |
| | | try |
| | | { |
| | | return shutdownRequested; |
| | | } |
| | | finally |
| | | { |
| | | queueReadLock.unlock(); |
| | | } |
| | | return shutdownRequested; |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | } |
| | | |
| | | private void submitOperation(Operation operation, |
| | | boolean blockEnqueuingWhenFull) throws DirectoryException |
| | | private void submitOperation(Operation operation, boolean blockEnqueuingWhenFull) throws DirectoryException |
| | | { |
| | | // Count the operation before enqueuing it so that isIdle() can never |
| | | // observe an empty queue while the operation is in the process of being |
| | | // submitted; the count is rolled back if the operation is rejected. |
| | | // Include the hand-off from the queue to a worker in the pending operation count. |
| | | pendingOpsCount.incrementAndGet(); |
| | | boolean submitted = false; |
| | | queueReadLock.lock(); |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | if (shutdownRequested) |
| | | checkForShutdown(); |
| | | if (blockEnqueuingWhenFull && Thread.interrupted()) |
| | | { |
| | | LocalizableMessage message = WARN_OP_REJECTED_BY_SHUTDOWN.get(); |
| | | throw new DirectoryException(ResultCode.UNAVAILABLE, message); |
| | | throw new InterruptedException(); |
| | | } |
| | | |
| | | if (blockEnqueuingWhenFull) |
| | | while (maxCapacity > 0 && opQueue.size() >= maxCapacity) |
| | | { |
| | | try |
| | | { |
| | | // If the queue is full and there is an administrative change taking |
| | | // place then starvation could arise: this thread will hold the read |
| | | // lock, the admin thread will be waiting on the write lock, and the |
| | | // worker threads may be queued behind the admin thread. Since the |
| | | // worker threads cannot run, the queue will never empty and allow |
| | | // this thread to proceed. To help things out we can periodically |
| | | // yield the read lock when the queue is full. |
| | | while (!opQueue.offer(operation, 1, TimeUnit.SECONDS)) |
| | | { |
| | | queueReadLock.unlock(); |
| | | Thread.yield(); |
| | | queueReadLock.lock(); |
| | | |
| | | if (shutdownRequested) |
| | | { |
| | | LocalizableMessage message = WARN_OP_REJECTED_BY_SHUTDOWN.get(); |
| | | throw new DirectoryException(ResultCode.UNAVAILABLE, message); |
| | | } |
| | | } |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | // We cannot handle the interruption here. Reject the request and |
| | | // re-interrupt this thread. |
| | | Thread.currentThread().interrupt(); |
| | | |
| | | queueFullRejects.incrementAndGet(); |
| | | |
| | | LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get(); |
| | | throw new DirectoryException(ResultCode.BUSY, message); |
| | | } |
| | | } |
| | | else |
| | | { |
| | | if (!opQueue.offer(operation)) |
| | | if (!blockEnqueuingWhenFull) |
| | | { |
| | | queueFullRejects.incrementAndGet(); |
| | | |
| | | LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_FULL.get(maxCapacity); |
| | | throw new DirectoryException(ResultCode.BUSY, message); |
| | | throw new DirectoryException(ResultCode.BUSY, WARN_OP_REJECTED_BY_QUEUE_FULL.get(maxCapacity)); |
| | | } |
| | | spaceAvailable.await(); |
| | | checkForShutdown(); |
| | | } |
| | | |
| | | opQueue.addLast(operation); |
| | | opsSubmitted.incrementAndGet(); |
| | | submitted = true; |
| | | workAvailable.signal(); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | Thread.currentThread().interrupt(); |
| | | queueFullRejects.incrementAndGet(); |
| | | throw new DirectoryException(ResultCode.BUSY, WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get()); |
| | | } |
| | | finally |
| | | { |
| | |
| | | { |
| | | pendingOpsCount.decrementAndGet(); |
| | | } |
| | | queueReadLock.unlock(); |
| | | queueLock.unlock(); |
| | | } |
| | | } |
| | | |
| | | private void checkForShutdown() throws DirectoryException |
| | | { |
| | | if (submissionsClosed || shutdownRequested) |
| | | { |
| | | throw new DirectoryException(ResultCode.UNAVAILABLE, WARN_OP_REJECTED_BY_SHUTDOWN.get()); |
| | | } |
| | | } |
| | | |
| | |
| | | * if the server is shutting down and no more operations will be |
| | | * processed, or if there have been too many consecutive failures. |
| | | */ |
| | | private Operation retryNextOperation(TraditionalWorkerThread workerThread, |
| | | int numFailures) |
| | | private Operation retryNextOperation(TraditionalWorkerThread workerThread, int numFailures) |
| | | { |
| | | // See if we should kill off this thread. This could be necessary if the |
| | | // number of worker threads has been decreased with the server online. If |
| | | // so, then return null and the thread will exit. |
| | | queueReadLock.lock(); |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | if (shutdownRequested) |
| | | while (!shutdownRequested) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | if (killThreads && tryKillThisWorkerThread(workerThread)) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | if (numFailures > MAX_RETRY_COUNT) |
| | | { |
| | | logger.error(ERR_CONFIG_WORK_QUEUE_TOO_MANY_FAILURES, Thread |
| | | .currentThread().getName(), numFailures, MAX_RETRY_COUNT); |
| | | |
| | | return null; |
| | | } |
| | | |
| | | while (true) |
| | | { |
| | | Operation nextOperation = opQueue.poll(5, TimeUnit.SECONDS); |
| | | if (nextOperation != null) |
| | | { |
| | | return nextOperation; |
| | | } |
| | | |
| | | // There was no work to do in the specified length of time. Release the |
| | | // read lock allowing shutdown or config changes to proceed and then see |
| | | // if we should give up or check again. |
| | | queueReadLock.unlock(); |
| | | Thread.yield(); |
| | | queueReadLock.lock(); |
| | | |
| | | if (shutdownRequested) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | if (killThreads && tryKillThisWorkerThread(workerThread)) |
| | | { |
| | | return null; |
| | | } |
| | | if (numFailures > MAX_RETRY_COUNT) |
| | | { |
| | | logger.error(ERR_CONFIG_WORK_QUEUE_TOO_MANY_FAILURES, |
| | | Thread.currentThread().getName(), numFailures, MAX_RETRY_COUNT); |
| | | return null; |
| | | } |
| | | if (Thread.interrupted()) |
| | | { |
| | | throw new InterruptedException(); |
| | | } |
| | | Operation nextOperation = opQueue.pollFirst(); |
| | | if (nextOperation != null) |
| | | { |
| | | spaceAvailable.signal(); |
| | | return nextOperation; |
| | | } |
| | | workAvailable.await(); |
| | | } |
| | | return null; |
| | | } |
| | | catch (InterruptedException ie) |
| | | catch (InterruptedException e) |
| | | { |
| | | // This is somewhat expected so don't log. |
| | | // assert debugException(CLASS_NAME, "retryNextOperation", ie); |
| | | |
| | | // If this occurs, then the worker thread must have been interrupted for |
| | | // some reason. This could be because the Directory Server is shutting |
| | | // down, in which case we should return null. |
| | | if (shutdownRequested) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | // If we've gotten here, then the worker thread was interrupted for some |
| | | // other reason. This should not happen, and we need to log a message. |
| | | logger.warn(WARN_WORKER_INTERRUPTED_WITHOUT_SHUTDOWN, Thread.currentThread().getName(), ie); |
| | | logger.warn(WARN_WORKER_INTERRUPTED_WITHOUT_SHUTDOWN, Thread.currentThread().getName(), e); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | |
| | | // This should not happen. The only recourse we have is to log a message |
| | | // and try again. |
| | | logger.warn(WARN_WORKER_WAITING_UNCAUGHT_EXCEPTION, Thread.currentThread().getName(), e); |
| | | } |
| | | finally |
| | | { |
| | | queueReadLock.unlock(); |
| | | queueLock.unlock(); |
| | | } |
| | | |
| | | // An exception has occurred - retry. |
| | | return retryNextOperation(workerThread, numFailures + 1); |
| | | } |
| | | |
| | | /** |
| | | * Kills this worker thread if needed. This method assumes that the read lock |
| | | * is already taken and ensure that it is taken on exit. |
| | | * |
| | | * @param workerThread |
| | | * The worker thread associated with this thread. |
| | | * @return {@code true} if this thread was killed or is about to be killed as |
| | | * a result of shutdown. |
| | | */ |
| | | /** Retires an excess worker while holding the queue lock. */ |
| | | private boolean tryKillThisWorkerThread(TraditionalWorkerThread workerThread) |
| | | { |
| | | queueReadLock.unlock(); |
| | | queueWriteLock.lock(); |
| | | try |
| | | if (workerThreads.size() <= numWorkerThreads) |
| | | { |
| | | if (shutdownRequested) |
| | | { |
| | | // Shutdown may have been requested between unlock/lock. This thread is |
| | | // about to shutdown anyway, so return true. |
| | | return true; |
| | | } |
| | | |
| | | int currentThreads = workerThreads.size(); |
| | | if (currentThreads > numWorkerThreads) |
| | | { |
| | | if (workerThreads.remove(Thread.currentThread())) |
| | | { |
| | | currentThreads--; |
| | | } |
| | | |
| | | if (currentThreads <= numWorkerThreads) |
| | | { |
| | | killThreads = false; |
| | | } |
| | | |
| | | workerThread.setStoppedByReducedThreadNumber(); |
| | | return true; |
| | | } |
| | | killThreads = false; |
| | | return false; |
| | | } |
| | | finally |
| | | { |
| | | queueWriteLock.unlock(); |
| | | queueReadLock.lock(); |
| | | |
| | | if (shutdownRequested) |
| | | { |
| | | // Shutdown may have been requested between unlock/lock. This thread is |
| | | // about to shutdown anyway, so return true. |
| | | return true; |
| | | } |
| | | } |
| | | return false; |
| | | workerThreads.remove(workerThread); |
| | | killThreads = workerThreads.size() > numWorkerThreads; |
| | | workerThread.setStoppedByReducedThreadNumber(); |
| | | return true; |
| | | } |
| | | |
| | | /** |
| | |
| | | |
| | | /** |
| | | * Retrieves the number of pending operations in the queue that have not yet |
| | | * been picked up for processing. Note that this method is not a constant-time |
| | | * operation and can be relatively inefficient, so it should be used |
| | | * sparingly. |
| | | * been picked up for processing. |
| | | * |
| | | * @return The number of pending operations in the queue that have not yet |
| | | * been picked up for processing. |
| | | */ |
| | | public int size() |
| | | { |
| | | queueReadLock.lock(); |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | return opQueue.size(); |
| | | } |
| | | finally |
| | | { |
| | | queueReadLock.unlock(); |
| | | queueLock.unlock(); |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | |
| | | @Override |
| | | public ConfigChangeResult applyConfigurationChange( |
| | | TraditionalWorkQueueCfg configuration) |
| | | public ConfigChangeResult applyConfigurationChange(TraditionalWorkQueueCfg configuration) |
| | | { |
| | | int newNumThreads = |
| | | computeNumWorkerThreads(configuration.getNumWorkerThreads()); |
| | | int newMaxCapacity = configuration.getMaxWorkQueueCapacity(); |
| | | |
| | | // Apply a change to the number of worker threads if appropriate. |
| | | int currentThreads = workerThreads.size(); |
| | | if (newNumThreads != currentThreads) |
| | | int newNumThreads = computeNumWorkerThreads(configuration.getNumWorkerThreads()); |
| | | queueLock.lock(); |
| | | try |
| | | { |
| | | queueWriteLock.lock(); |
| | | try |
| | | if (shutdownRequested) |
| | | { |
| | | int threadsToAdd = newNumThreads - currentThreads; |
| | | if (threadsToAdd > 0) |
| | | { |
| | | for (int i = 0; i < threadsToAdd; i++) |
| | | { |
| | | TraditionalWorkerThread t = new TraditionalWorkerThread(this, |
| | | lastThreadNumber++); |
| | | workerThreads.add(t); |
| | | t.start(); |
| | | } |
| | | return new ConfigChangeResult(); |
| | | } |
| | | int threadsToAdd = newNumThreads - workerThreads.size(); |
| | | for (int i = 0; i < threadsToAdd; i++) |
| | | { |
| | | TraditionalWorkerThread worker = new TraditionalWorkerThread(this, lastThreadNumber++); |
| | | workerThreads.add(worker); |
| | | worker.start(); |
| | | } |
| | | numWorkerThreads = newNumThreads; |
| | | killThreads = threadsToAdd < 0; |
| | | if (killThreads) |
| | | { |
| | | workAvailable.signalAll(); |
| | | } |
| | | |
| | | killThreads = false; |
| | | } |
| | | else |
| | | { |
| | | killThreads = true; |
| | | } |
| | | |
| | | numWorkerThreads = newNumThreads; |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | logger.traceException(e); |
| | | } |
| | | finally |
| | | { |
| | | queueWriteLock.unlock(); |
| | | } |
| | | // Keep queued work in FIFO order even when the new limit is below the backlog size. |
| | | maxCapacity = configuration.getMaxWorkQueueCapacity(); |
| | | spaceAvailable.signalAll(); |
| | | } |
| | | |
| | | // Apply a change to the maximum capacity if appropriate. Since we can't |
| | | // change capacity on the fly, then we'll have to create a new queue and |
| | | // transfer any remaining items into it. Any thread that is waiting on the |
| | | // original queue will time out after at most a few seconds and further |
| | | // checks will be against the new queue. |
| | | if (newMaxCapacity != maxCapacity) |
| | | finally |
| | | { |
| | | // First switch the queue with the exclusive lock. |
| | | queueWriteLock.lock(); |
| | | LinkedBlockingQueue<Operation> oldOpQueue; |
| | | try |
| | | { |
| | | LinkedBlockingQueue<Operation> newOpQueue = null; |
| | | if (newMaxCapacity > 0) |
| | | { |
| | | newOpQueue = new LinkedBlockingQueue<>(newMaxCapacity); |
| | | } |
| | | else |
| | | { |
| | | newOpQueue = new LinkedBlockingQueue<>(); |
| | | } |
| | | |
| | | oldOpQueue = opQueue; |
| | | opQueue = newOpQueue; |
| | | |
| | | maxCapacity = newMaxCapacity; |
| | | } |
| | | finally |
| | | { |
| | | queueWriteLock.unlock(); |
| | | } |
| | | |
| | | // Now resubmit any pending requests - we'll need the shared lock. |
| | | Operation pendingOperation = null; |
| | | queueReadLock.lock(); |
| | | try |
| | | { |
| | | // We have to be careful when adding any existing pending operations |
| | | // because the new capacity could be less than what was already |
| | | // backlogged in the previous queue. If that happens, we may have to |
| | | // loop a few times to get everything in there. |
| | | while ((pendingOperation = oldOpQueue.poll()) != null) |
| | | { |
| | | opQueue.put(pendingOperation); |
| | | } |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | // We cannot handle the interruption here. Cancel pending requests and |
| | | // re-interrupt this thread. |
| | | Thread.currentThread().interrupt(); |
| | | |
| | | LocalizableMessage message = WARN_OP_REJECTED_BY_QUEUE_INTERRUPT.get(); |
| | | CancelRequest cancelRequest = new CancelRequest(true, message); |
| | | if (pendingOperation != null) |
| | | { |
| | | pendingOperation.abort(cancelRequest); |
| | | pendingOpsCount.decrementAndGet(); |
| | | } |
| | | while ((pendingOperation = oldOpQueue.poll()) != null) |
| | | { |
| | | pendingOperation.abort(cancelRequest); |
| | | pendingOpsCount.decrementAndGet(); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | queueReadLock.unlock(); |
| | | } |
| | | queueLock.unlock(); |
| | | } |
| | | |
| | | return new ConfigChangeResult(); |
| | | } |
| | | |
| | |
| | | */ |
| | | private boolean stoppedByReducedThreadNumber; |
| | | |
| | | /** Indicates whether this thread is currently waiting for work. */ |
| | | private boolean waitingForWork; |
| | | /** Serializes publication of an operation with the shutdown request. */ |
| | | private final Object operationLock = new Object(); |
| | | |
| | | /** The operation that this worker thread is currently processing. */ |
| | | private volatile Operation operation; |
| | | |
| | | /** The handle to the actual thread for this worker thread. */ |
| | | private Thread workerThread; |
| | | |
| | | /** The work queue that this worker thread will service. */ |
| | | private final TraditionalWorkQueue workQueue; |
| | | |
| | |
| | | |
| | | stoppedByReducedThreadNumber = false; |
| | | shutdownRequested = false; |
| | | waitingForWork = false; |
| | | operation = null; |
| | | workerThread = null; |
| | | } |
| | | |
| | | |
| | |
| | | @Override |
| | | public void run() |
| | | { |
| | | workerThread = currentThread(); |
| | | |
| | | while (! shutdownRequested) |
| | | { |
| | | try |
| | | { |
| | | waitingForWork = true; |
| | | operation = null; // this line is necessary because next line can block |
| | | operation = workQueue.nextOperation(this); |
| | | waitingForWork = false; |
| | | |
| | | |
| | | if (operation == null) |
| | | operation = null; |
| | | Operation nextOperation = workQueue.nextOperation(this); |
| | | if (nextOperation == null) |
| | | { |
| | | // The operation may be null if the server is shutting down. If that |
| | | // is the case, then break out of the while loop. |
| | | break; |
| | | } |
| | | if (!startOperation(nextOperation)) |
| | | { |
| | | workQueue.abortPendingOperation(nextOperation, new CancelRequest(true, INFO_CANCELED_BY_SHUTDOWN.get())); |
| | | break; |
| | | } |
| | | else |
| | |
| | | logger.trace(getName() + " being signaled to shut down."); |
| | | } |
| | | |
| | | // Set a flag that indicates that the thread should stop running. |
| | | shutdownRequested = true; |
| | | |
| | | |
| | | // Check to see if the thread is waiting for work. If so, then interrupt |
| | | // it. |
| | | if (waitingForWork) |
| | | final Operation activeOperation; |
| | | synchronized (operationLock) |
| | | { |
| | | try |
| | | { |
| | | workerThread.interrupt(); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | logger.trace( |
| | | "Caught an exception while trying to interrupt the worker " + |
| | | "thread waiting for work: %s", e); |
| | | logger.traceException(e); |
| | | } |
| | | } |
| | | shutdownRequested = true; |
| | | activeOperation = operation; |
| | | } |
| | | else |
| | | if (activeOperation != null) |
| | | { |
| | | try |
| | | activeOperation.cancel(new CancelRequest(true, INFO_CANCELED_BY_SHUTDOWN.get())); |
| | | } |
| | | } |
| | | |
| | | private boolean startOperation(Operation nextOperation) |
| | | { |
| | | synchronized (operationLock) |
| | | { |
| | | if (shutdownRequested || workQueue.shutdownRequested()) |
| | | { |
| | | final Operation localOperation = operation; |
| | | if (localOperation != null) |
| | | { |
| | | CancelRequest cancelRequest = new CancelRequest(true, |
| | | INFO_CANCELED_BY_SHUTDOWN.get()); |
| | | localOperation.cancel(cancelRequest); |
| | | } |
| | | return false; |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | if (logger.isTraceEnabled()) |
| | | { |
| | | logger.trace( |
| | | "Caught an exception while trying to abandon the " + |
| | | "operation in progress for the worker thread: %s", e); |
| | | logger.traceException(e); |
| | | } |
| | | } |
| | | operation = nextOperation; |
| | | return true; |
| | | } |
| | | } |
| | | |
| | |
| | | * |
| | | * Copyright 2009 Sun Microsystems, Inc. |
| | | * Portions Copyright 2013-2015 ForgeRock AS. |
| | | * Portions Copyright 2018-2026 3A Systems, LLC |
| | | * Portions Copyright 2018-2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.quicksetup; |
| | | |
| | |
| | | } |
| | | |
| | | private static void setupServer() throws IOException, InterruptedException { |
| | | int[] ports = TestCaseUtils.findFreePorts(2); |
| | | int[] ports = TestCaseUtils.findFreePorts(3); |
| | | ldapPort = ports[0]; |
| | | jmxPort = ports[1]; |
| | | |
| | |
| | | args.add(Integer.toString(ldapPort)); |
| | | args.add("-x"); |
| | | args.add(Integer.toString(jmxPort)); |
| | | args.add("--adminConnectorPort"); |
| | | args.add(Integer.toString(ports[2])); |
| | | args.add("-w"); |
| | | args.add(DIRECTORY_MANAGER_PASSWORD); |
| | | // Create a backend so that configuration tests see database paths. |
| | |
| | | String buildRoot = System.getProperty(PROPERTY_BUILD_ROOT); |
| | | File buildDir = new File(buildRoot, "build"); |
| | | File unitRootDir = new File(buildDir, "unit-tests"); |
| | | return new File(unitRootDir, "quicksetup"); |
| | | return TestCaseUtils.getForkDirectory(new File(unitRootDir, "quicksetup")); |
| | | } |
| | | |
| | | public static File getQuickSetupTestServerRootDir() { |
| | |
| | | * |
| | | * Copyright 2006-2008 Sun Microsystems, Inc. |
| | | * Portions Copyright 2014-2015 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.quicksetup.util; |
| | | |
| | |
| | | @Test |
| | | public void testRenameNonExistentTarget() throws Exception { |
| | | File src = File.createTempFile("src", null); |
| | | File target = new File(src.getParentFile(), "target"); |
| | | File target = File.createTempFile("target", null); |
| | | try { |
| | | if (target.exists()) { |
| | | target.delete(); |
| | | assertFalse(target.exists()); |
| | | } |
| | | assertTrue(target.delete()); |
| | | fileManager.rename(src, target); |
| | | assertFalse(src.exists()); |
| | | assertTrue(target.exists()); |
| | |
| | | * Copyright 2006-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2013 Manuel Gaupp |
| | | * Portions Copyright 2018-2026 3A Systems, LLC |
| | | * Portions Copyright 2018-2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server; |
| | | |
| | |
| | | * |
| | | * @throws IOException in case of underlying exception. |
| | | */ |
| | | private static ServerSocket bindPort(int port) |
| | | throws IOException |
| | | private static ServerSocket bindPort(int port) throws IOException |
| | | { |
| | | ServerSocket serverLdapSocket; |
| | | serverLdapSocket = new ServerSocket(); |
| | | serverLdapSocket.setReuseAddress(true); |
| | | serverLdapSocket.bind(new InetSocketAddress(port)); |
| | | return serverLdapSocket; |
| | | ServerSocket socket = new ServerSocket(); |
| | | try |
| | | { |
| | | socket.setReuseAddress(true); |
| | | socket.bind(new InetSocketAddress(port)); |
| | | return socket; |
| | | } |
| | | catch (IOException e) |
| | | { |
| | | close(socket); |
| | | throw e; |
| | | } |
| | | } |
| | | |
| | | static int port = 65535; |
| | | private static final int TEST_FORK_COUNT = Math.max(1, |
| | | Integer.parseInt(System.getProperty("org.opends.test.forkCount", "1"))); |
| | | private static final int TEST_FORK_NUMBER = Integer.getInteger("org.opends.test.forkNumber", 0); |
| | | private static int nextTestPort = firstTestPort(); |
| | | |
| | | private static int firstTestPort() |
| | | { |
| | | if (TEST_FORK_COUNT == 1) |
| | | { |
| | | return 65535; |
| | | } |
| | | if (TEST_FORK_NUMBER < 1 || TEST_FORK_NUMBER > TEST_FORK_COUNT) |
| | | { |
| | | throw new IllegalStateException("Expected a Failsafe fork number between 1 and " + TEST_FORK_COUNT |
| | | + ", got " + System.getProperty("org.opends.test.forkNumber")); |
| | | } |
| | | // Concurrent forks start below the Linux ephemeral range and each walks its own sequence. |
| | | return 32768 - TEST_FORK_NUMBER; |
| | | } |
| | | |
| | | /** |
| | | * Find and binds to a free server socket port on the local host. Avoid allocating ephemeral ports since these may |
| | | * be used by client applications such as dsconfig. Instead scan through ports starting from a reasonably high number |
| | | * which avoids most reserved services (see /etc/services) and continues up to the beginning of the ephemeral port |
| | | * range. On most Linux OSes this is 32768, but may be higher. |
| | | * Finds and binds a free server socket port on the local host. |
| | | * In parallel precommit runs each fork allocates from a disjoint sequence below the Linux |
| | | * ephemeral range, so another fork cannot claim a port between discovery and server startup. |
| | | * |
| | | * @return the bounded Server socket. |
| | | * |
| | | * @throws IOException in case of underlying exception. |
| | | * @return The bound server socket. |
| | | * @throws IOException If unable to bind to a free port. |
| | | */ |
| | | public synchronized static ServerSocket bindFreePort() throws IOException |
| | | { |
| | | for (; port > 1024;) |
| | | { |
| | | ServerSocket res=null; |
| | | try |
| | | { |
| | | res=bindPort(port--); |
| | | return res; |
| | | } |
| | | catch (BindException e){ |
| | | if (res!=null) { |
| | | try { |
| | | res.close(); |
| | | } catch (IOException ex) {} |
| | | } |
| | | res=null; |
| | | } |
| | | } |
| | | throw new BindException("Unable to bind to a free port"); |
| | | while (nextTestPort > 1024) |
| | | { |
| | | int candidate = nextTestPort; |
| | | nextTestPort -= TEST_FORK_COUNT; |
| | | try |
| | | { |
| | | return bindPort(candidate); |
| | | } |
| | | catch (BindException e) |
| | | { |
| | | // The candidate is already in use. Try the next port assigned to this fork. |
| | | } |
| | | } |
| | | throw new BindException("Unable to bind to a free port"); |
| | | } |
| | | |
| | | /** |
| | | * Returns a fork-specific subdirectory when more than one test JVM is active. |
| | | */ |
| | | public static File getForkDirectory(File directory) |
| | | { |
| | | return TEST_FORK_COUNT > 1 ? new File(directory, "fork-" + TEST_FORK_NUMBER) : directory; |
| | | } |
| | | |
| | | /** |
| | |
| | | } |
| | | |
| | | // Delete the previous report if it's there. |
| | | new File(testContext.getOutputDirectory(), REPORT_FILE_NAME).delete(); |
| | | new File(getForkDirectory(new File(testContext.getOutputDirectory())), REPORT_FILE_NAME).delete(); |
| | | } |
| | | |
| | | @Override |
| | |
| | | |
| | | @Override |
| | | public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) { |
| | | File outputDir = new File(outputDirectory); |
| | | File outputDir = getForkDirectory(new File(outputDirectory)); |
| | | if (!outputDir.exists()) { |
| | | outputDir.mkdir(); |
| | | outputDir.mkdirs(); |
| | | } |
| | | |
| | | File reportFile = new File(outputDirectory, REPORT_FILE_NAME); |
| | | File reportFile = new File(outputDir, REPORT_FILE_NAME); |
| | | |
| | | writeReportToFile(reportFile); |
| | | writeReportToScreen(reportFile); |
| | | writeAntTestsFailedMarker(outputDirectory); |
| | | writeAntTestsFailedMarker(outputDir); |
| | | } |
| | | |
| | | private void writeAntTestsFailedMarker(String outputDirectory) { |
| | | private void writeAntTestsFailedMarker(File outputDirectory) { |
| | | // Signal 'ant' that all of the tests passed by removing this |
| | | // special file. |
| | | if (countTestsWithStatus(ITestResult.FAILURE) == 0 |
| | |
| | | |
| | | import static org.opends.server.TestCaseUtils.*; |
| | | import static org.opends.server.config.ConfigConstants.*; |
| | | import static org.opends.server.protocols.internal.InternalClientConnection.getRootConnection; |
| | | import static org.opends.server.util.CollectionUtils.*; |
| | | import static org.opends.server.util.ServerConstants.*; |
| | | import static org.testng.Assert.*; |
| | |
| | | |
| | | import com.forgerock.opendj.ldap.tools.LDAPCompare; |
| | | import com.forgerock.opendj.ldap.tools.LDIFDiff; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.core.DeleteOperation; |
| | | import org.opends.server.protocols.ldap.LDAPResultCode; |
| | | import com.forgerock.opendj.ldap.tools.LDAPModify; |
| | | import com.forgerock.opendj.ldap.tools.LDAPSearch; |
| | |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** |
| | | * These are more functional tests than unit tests. They go directly over |
| | | * LDAP for all of their operations. We use the builtin LDAPModify, |
| | | * These functional tests exercise ACI behavior over LDAP. We use the builtin LDAPModify, |
| | | * LDAPSearch, etc. tools to do this, as well as the ones that can |
| | | * do similar operations directly on LDIF (e.g. LDIFDiff). This is |
| | | * probably the easiest way to test the code, and it makes it easy to test |
| | |
| | | private static final String PROXY_USER_DN = "cn=proxy user," + OU_BASE_DN; |
| | | |
| | | /** |
| | | * We need to delete all of these between each test. This list needs to be |
| | | * bottom up so that it can be handed to LDAPDelete. |
| | | * Test entries in deletion order, with child entries before their parents. |
| | | */ |
| | | private static final String[] ALL_TEST_ENTRY_DNS_BOTTOM_UP = { |
| | | SALES_USER_1, |
| | |
| | | |
| | | |
| | | @BeforeMethod |
| | | public void clearBackend() throws Exception { |
| | | deleteAllTestEntries(); |
| | | public void clearBackend() { |
| | | // Wait for post-response delete plugins before the next test reuses the same DNs. |
| | | // An LDAP delete can return while AuthenticatedUsers is still processing the deletion. |
| | | for (String dn : ALL_TEST_ENTRY_DNS_BOTTOM_UP) { |
| | | DeleteOperation delete = getRootConnection().processDelete(dn); |
| | | ResultCode result = delete.getResultCode(); |
| | | assertTrue(result == ResultCode.SUCCESS || result == ResultCode.NO_SUCH_OBJECT, |
| | | "Could not delete test entry " + dn + " (" + result + ") " + delete.getErrorMessage()); |
| | | } |
| | | } |
| | | |
| | | // ----------------------------------------------------------------------------- |
| | |
| | | |
| | | private void modEntries(String ldif, String bindDn, String bindPassword) |
| | | throws Exception { |
| | | modEntries(ldif, bindDn, bindPassword, null, true, false); |
| | | modEntries(ldif, bindDn, bindPassword, null, true); |
| | | } |
| | | |
| | | private void modEntries(String ldif, String bindDn, String bindPassword, String proxyDN) |
| | | throws Exception { |
| | | modEntries(ldif, bindDn, bindPassword, proxyDN, true, false); |
| | | modEntries(ldif, bindDn, bindPassword, proxyDN, true); |
| | | } |
| | | |
| | | private void modEntriesExpectFailure(String ldif, String bindDn, |
| | | String bindPassword) throws Exception { |
| | | modEntries(ldif, bindDn, bindPassword, null, false, false); |
| | | modEntries(ldif, bindDn, bindPassword, null, false); |
| | | } |
| | | |
| | | private void _modEntries(String ldif, String bindDn, String bindPassword, |
| | |
| | | } |
| | | |
| | | private void modEntries(String ldif, String bindDn, String bindPassword, |
| | | String proxyDN, boolean expectSuccess, |
| | | boolean contFlag) |
| | | String proxyDN, boolean expectSuccess) |
| | | throws Exception { |
| | | File tempFile = getTemporaryLdifFile(); |
| | | TestCaseUtils.writeFile(tempFile, ldif); |
| | |
| | | argList.add(bindPassword); |
| | | argList.add("-f"); |
| | | argList.add(tempFile.getAbsolutePath()); |
| | | if(contFlag) |
| | | { |
| | | argList.add("-c"); |
| | | } |
| | | if(proxyDN != null) { |
| | | argList.add("-Y"); |
| | | argList.add("dn:" + proxyDN); |
| | |
| | | ldapModify(argList.toArray(args), expectSuccess); |
| | | } |
| | | |
| | | private void deleteAllTestEntries() throws Exception { |
| | | deleteEntries(ALL_TEST_ENTRY_DNS_BOTTOM_UP); |
| | | } |
| | | |
| | | private void deleteAttrFromEntry(String dn, String attr, String val, |
| | | String bindDN, String pwd, |
| | | boolean errorOk) throws Exception { |
| | |
| | | "changetype: modify", |
| | | "delete: " + attr, |
| | | attr + ":" + val)); |
| | | modEntries(ldif.toString(), bindDN, pwd, null, errorOk, false); |
| | | modEntries(ldif.toString(), bindDN, pwd, null, errorOk); |
| | | } |
| | | |
| | | |
| | |
| | | "dn: " + dn, |
| | | "changetype: modify", |
| | | "delete: " + attr)); |
| | | modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW, null, errorOk, false); |
| | | modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW, null, errorOk); |
| | | } |
| | | |
| | | private void deleteEntries(String[] entries) throws Exception { |
| | | // TODO: make this actually do a search first! |
| | | StringBuilder ldif = new StringBuilder(); |
| | | for (String dn: entries) { |
| | | ldif.append(TestCaseUtils.makeLdif( |
| | | "dn: " + dn, |
| | | "changetype: delete" |
| | | )); |
| | | } |
| | | modEntries(ldif.toString(), DIR_MGR_DN, DIR_MGR_PW, null, true, true); |
| | | } |
| | | |
| | | /** |
| | | * Return the difference between two ldif files. |
| | | */ |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Tests the <CODE>cancel</CODE> method to ensure that it indicates that the |
| | | * operation cannot be cancelled. |
| | | * @param bindOperation The bind operation. |
| | | */ |
| | | @Test(dataProvider = "simpleBinds") |
| | | public void testCancel(BindOperation bindOperation) |
| | | public void testCancelCompletedBind(BindOperation bindOperation) |
| | | { |
| | | CancelRequest cancelRequest = |
| | | new CancelRequest(false, LocalizableMessage.raw("Test Unbind Cancel")); |
| | | |
| | | assertEquals(bindOperation.cancel(cancelRequest).getResultCode(), |
| | | ResultCode.CANNOT_CANCEL); |
| | | bindOperation.operationCompleted(); |
| | | assertBindCannotBeCancelled(bindOperation); |
| | | } |
| | | |
| | | /** |
| | | * Tests the <CODE>getCancelRequest</CODE> method to ensure that it always |
| | | * returns <CODE>null</CODE>. |
| | | * @param bindOperation The bind operation. |
| | | */ |
| | | @Test(dataProvider = "simpleBinds") |
| | | public void testGetCancelRequest(BindOperation bindOperation) |
| | | @Test |
| | | public void testCancelUnfinishedBind() |
| | | { |
| | | assertBindCannotBeCancelled(newBindOp(null, ByteString.empty(), ByteString.empty())); |
| | | } |
| | | |
| | | private void assertBindCannotBeCancelled(BindOperation bindOperation) |
| | | { |
| | | CancelRequest cancelRequest = |
| | | new CancelRequest(false, LocalizableMessage.raw("Test Unbind Cancel")); |
| | | new CancelRequest(false, LocalizableMessage.raw("Test Bind Cancel")); |
| | | |
| | | assertNull(bindOperation.getCancelRequest()); |
| | | |
| New file |
| | |
| | | /* |
| | | * The contents of this file are subject to the terms of the Common Development and |
| | | * Distribution License (the License). You may not use this file except in compliance with the |
| | | * License. |
| | | * |
| | | * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the |
| | | * specific language governing permission and limitations under the License. |
| | | * |
| | | * When distributing Covered Software, include this CDDL Header Notice in each file and include |
| | | * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL |
| | | * Header, with the fields enclosed by brackets [] replaced by your own identifying |
| | | * information: "Portions copyright [year] [name of copyright owner]". |
| | | * |
| | | * Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.extensions; |
| | | |
| | | import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| | | import static java.util.concurrent.TimeUnit.SECONDS; |
| | | import static org.mockito.Mockito.*; |
| | | import static org.testng.Assert.*; |
| | | |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.FutureTask; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.opendj.ldap.ResultCode; |
| | | import org.forgerock.opendj.server.config.server.TraditionalWorkQueueCfg; |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.types.CancelRequest; |
| | | import org.opends.server.types.DirectoryException; |
| | | import org.opends.server.types.Operation; |
| | | import org.opends.server.util.TestTimer; |
| | | import org.testng.annotations.Test; |
| | | |
| | | /** Verifies that shutting down a traditional work queue wakes idle workers and accounts for pending work. */ |
| | | public class TraditionalWorkQueueShutdownTest extends DirectoryServerTestCase |
| | | { |
| | | private static final LocalizableMessage SHUTDOWN_REASON = LocalizableMessage.raw("Test work queue shutdown"); |
| | | |
| | | @Test |
| | | public void wakesAnIdleWorkerBeforeThePollExpires() throws Exception |
| | | { |
| | | TestWorkQueue queue = new TestWorkQueue(); |
| | | queue.initializeWorkQueue(config(10)); |
| | | try |
| | | { |
| | | waitForIdleWorker(queue); |
| | | } |
| | | finally |
| | | { |
| | | long start = System.nanoTime(); |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | assertTrue(System.nanoTime() - start < SECONDS.toNanos(3), |
| | | "Shutdown waited for the idle worker's five-second poll"); |
| | | } |
| | | queue.worker.join(SECONDS.toMillis(3)); |
| | | assertFalse(queue.worker.isAlive(), "The idle worker did not exit"); |
| | | assertTrue(queue.isIdle()); |
| | | } |
| | | |
| | | @Test |
| | | public void accountsForDrainedOperationsWithoutInterruptingAnActiveWorker() throws Exception |
| | | { |
| | | CountDownLatch running = new CountDownLatch(1); |
| | | CountDownLatch finish = new CountDownLatch(1); |
| | | CountDownLatch interrupted = new CountDownLatch(1); |
| | | TestWorkQueue queue = new TestWorkQueue(); |
| | | queue.initializeWorkQueue(config(10)); |
| | | Operation active = mock(Operation.class); |
| | | doAnswer(invocation -> { |
| | | running.countDown(); |
| | | try |
| | | { |
| | | finish.await(); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | interrupted.countDown(); |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | return null; |
| | | }).when(active).run(); |
| | | Operation pending = mock(Operation.class); |
| | | try |
| | | { |
| | | queue.submitOperation(active); |
| | | assertTrue(running.await(5, SECONDS), "Worker did not begin the active operation"); |
| | | queue.submitOperation(pending); |
| | | Operation anotherPending = mock(Operation.class); |
| | | queue.submitOperation(anotherPending); |
| | | queue.applyConfigurationChange(config(1)); |
| | | assertFalse(queue.trySubmitOperation(mock(Operation.class)), "The smaller queue is full"); |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | verify(active).cancel(any(CancelRequest.class)); |
| | | verify(anotherPending).abort(any(CancelRequest.class)); |
| | | verify(anotherPending, never()).run(); |
| | | verify(pending).abort(any(CancelRequest.class)); |
| | | verify(pending, never()).run(); |
| | | assertFalse(queue.isIdle(), "The active operation is still pending"); |
| | | } |
| | | finally |
| | | { |
| | | finish.countDown(); |
| | | if (!queue.shutdownRequested()) |
| | | { |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | } |
| | | } |
| | | assertTrue(queue.waitUntilIdle(1000), "The drained operation still counts as pending"); |
| | | assertEquals(interrupted.getCount(), 1L, "Shutdown interrupted a worker processing an operation"); |
| | | } |
| | | |
| | | @Test |
| | | public void stoppingAdmissionWakesAllBlockedSubmittersBeforeFinalization() throws Exception |
| | | { |
| | | CountDownLatch running = new CountDownLatch(1); |
| | | CountDownLatch finish = new CountDownLatch(1); |
| | | TestWorkQueue queue = new TestWorkQueue(); |
| | | queue.initializeWorkQueue(config(1)); |
| | | Operation active = mock(Operation.class); |
| | | doAnswer(invocation -> { |
| | | running.countDown(); |
| | | finish.await(); |
| | | return null; |
| | | }).when(active).run(); |
| | | Operation queued = mock(Operation.class); |
| | | try |
| | | { |
| | | queue.submitOperation(active); |
| | | assertTrue(running.await(5, SECONDS), "Worker did not begin the active operation"); |
| | | queue.submitOperation(queued); |
| | | FutureTask<ResultCode> first = startBlockedSubmitter(queue, "First submitter"); |
| | | FutureTask<ResultCode> second = startBlockedSubmitter(queue, "Second submitter"); |
| | | |
| | | queue.stopAcceptingOperations(); |
| | | |
| | | assertEquals(first.get(5, SECONDS), ResultCode.UNAVAILABLE, "First submitter was not rejected"); |
| | | assertEquals(second.get(5, SECONDS), ResultCode.UNAVAILABLE, "Second submitter was not rejected"); |
| | | DirectoryException rejection = expectThrows(DirectoryException.class, |
| | | () -> queue.trySubmitOperation(mock(Operation.class))); |
| | | assertEquals(rejection.getResultCode(), ResultCode.UNAVAILABLE); |
| | | assertFalse(queue.shutdownRequested(), "Stopping admission stopped the worker pool"); |
| | | assertEquals(queue.size(), 1, "Stopping admission drained the queue"); |
| | | verify(active, never()).cancel(any(CancelRequest.class)); |
| | | verify(active, never()).operationCompleted(); |
| | | verify(queued, never()).abort(any(CancelRequest.class)); |
| | | } |
| | | finally |
| | | { |
| | | try |
| | | { |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | } |
| | | finally |
| | | { |
| | | finish.countDown(); |
| | | } |
| | | } |
| | | verify(active).cancel(any(CancelRequest.class)); |
| | | verify(queued).abort(any(CancelRequest.class)); |
| | | assertTrue(queue.waitUntilIdle(1000), "Rejected submissions or canceled operations still count as pending"); |
| | | } |
| | | |
| | | @Test |
| | | public void abortsADequeuedOperationWhenShutdownWinsTheHandoff() throws Exception |
| | | { |
| | | CountDownLatch dequeued = new CountDownLatch(1); |
| | | CountDownLatch handoff = new CountDownLatch(1); |
| | | TestWorkQueue queue = new TestWorkQueue() |
| | | { |
| | | @Override |
| | | public Operation nextOperation(TraditionalWorkerThread worker) |
| | | { |
| | | Operation operation = super.nextOperation(worker); |
| | | if (operation != null) |
| | | { |
| | | dequeued.countDown(); |
| | | try |
| | | { |
| | | assertTrue(handoff.await(5, SECONDS), "Timed out waiting for handoff to resume"); |
| | | } |
| | | catch (InterruptedException e) |
| | | { |
| | | throw new AssertionError("Shutdown interrupted the handoff", e); |
| | | } |
| | | } |
| | | return operation; |
| | | } |
| | | }; |
| | | queue.initializeWorkQueue(config(10)); |
| | | Operation pending = mock(Operation.class); |
| | | try |
| | | { |
| | | queue.submitOperation(pending); |
| | | assertTrue(dequeued.await(5, SECONDS), "Worker did not dequeue the operation"); |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | assertFalse(queue.isIdle(), "The dequeued operation is still in the handoff"); |
| | | } |
| | | finally |
| | | { |
| | | handoff.countDown(); |
| | | if (!queue.shutdownRequested()) |
| | | { |
| | | queue.finalizeWorkQueue(SHUTDOWN_REASON); |
| | | } |
| | | } |
| | | assertTrue(queue.waitUntilIdle(1000), "The handoff operation was not aborted"); |
| | | verify(pending).abort(any(CancelRequest.class)); |
| | | verify(pending, never()).run(); |
| | | } |
| | | |
| | | private TraditionalWorkQueueCfg config(int capacity) |
| | | { |
| | | TraditionalWorkQueueCfg config = mock(TraditionalWorkQueueCfg.class); |
| | | when(config.getNumWorkerThreads()).thenReturn(1); |
| | | when(config.getMaxWorkQueueCapacity()).thenReturn(capacity); |
| | | return config; |
| | | } |
| | | |
| | | private void waitForIdleWorker(TestWorkQueue queue) throws Exception |
| | | { |
| | | new TestTimer.Builder().maxSleep(5, SECONDS).sleepTimes(10, MILLISECONDS).toTimer().repeatUntilSuccess(() -> { |
| | | Thread worker = queue.worker; |
| | | assertNotNull(worker, "Worker has not started"); |
| | | assertWaitingInQueue(worker, "retryNextOperation"); |
| | | }); |
| | | } |
| | | |
| | | private FutureTask<ResultCode> startBlockedSubmitter(TestWorkQueue queue, String name) throws Exception |
| | | { |
| | | Operation operation = mock(Operation.class); |
| | | FutureTask<ResultCode> submission = new FutureTask<>(() -> |
| | | expectThrows(DirectoryException.class, () -> queue.submitOperation(operation)).getResultCode()); |
| | | Thread thread = new Thread(submission, name); |
| | | thread.setDaemon(true); |
| | | thread.start(); |
| | | new TestTimer.Builder().maxSleep(5, SECONDS).sleepTimes(10, MILLISECONDS).toTimer().repeatUntilSuccess( |
| | | () -> assertWaitingInQueue(thread, "submitOperation")); |
| | | return submission; |
| | | } |
| | | |
| | | private void assertWaitingInQueue(Thread thread, String methodName) |
| | | { |
| | | assertEquals(thread.getState(), Thread.State.WAITING, thread.getName() + " has not entered the condition wait"); |
| | | StackTraceElement[] stack = thread.getStackTrace(); |
| | | for (int i = 1; i < stack.length; i++) |
| | | { |
| | | StackTraceElement frame = stack[i]; |
| | | if (frame.getClassName().equals(TraditionalWorkQueue.class.getName()) |
| | | && frame.getMethodName().equals(methodName) |
| | | && stack[i - 1].getMethodName().equals("await")) |
| | | { |
| | | return; |
| | | } |
| | | } |
| | | fail(thread.getName() + " has not reached the queue wait"); |
| | | } |
| | | |
| | | private static class TestWorkQueue extends TraditionalWorkQueue |
| | | { |
| | | private volatile TraditionalWorkerThread worker; |
| | | |
| | | @Override |
| | | void registerQueueMonitor() |
| | | { |
| | | // This queue is local to the test and has no server monitor. |
| | | } |
| | | |
| | | @Override |
| | | public Operation nextOperation(TraditionalWorkerThread workerThread) |
| | | { |
| | | worker = workerThread; |
| | | return super.nextOperation(workerThread); |
| | | } |
| | | } |
| | | } |
| | |
| | | */ |
| | | package org.opends.server.protocols.ldap; |
| | | |
| | | import static java.util.Arrays.stream; |
| | | import static java.util.Collections.singletonList; |
| | | import static java.util.concurrent.TimeUnit.MILLISECONDS; |
| | | import static org.forgerock.opendj.ldap.LDAPConnectionFactory.SSL_CONTEXT; |
| | | import static org.forgerock.opendj.ldap.ModificationType.REPLACE; |
| | | import static org.forgerock.opendj.ldap.requests.Requests.*; |
| | | import static org.mockito.Mockito.*; |
| | | import static org.opends.messages.CoreMessages.INFO_CONNHANDLER_CLOSED_BY_SHUTDOWN; |
| | | import static org.testng.Assert.*; |
| | | |
| | |
| | | import java.net.SocketTimeoutException; |
| | | import java.nio.channels.ServerSocketChannel; |
| | | import java.nio.channels.SocketChannel; |
| | | import java.nio.file.Files; |
| | | import java.nio.file.Paths; |
| | | import java.util.ArrayList; |
| | | import java.util.Collection; |
| | | import java.util.List; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Executors; |
| | | import java.util.concurrent.Future; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | import org.forgerock.i18n.LocalizableMessage; |
| | | import org.forgerock.opendj.ldap.Connection; |
| | | import org.forgerock.opendj.ldap.DN; |
| | | import org.forgerock.opendj.ldap.LDAPConnectionFactory; |
| | | import org.forgerock.opendj.ldap.LdapPromise; |
| | | import org.forgerock.opendj.ldap.SSLContextBuilder; |
| | | import org.forgerock.opendj.ldap.responses.Result; |
| | | import org.forgerock.opendj.ldif.LDIFEntryReader; |
| | | import org.forgerock.opendj.reactive.LDAPConnectionHandler2; |
| | | import org.forgerock.opendj.server.config.meta.LDAPConnectionHandlerCfgDefn; |
| | | import org.forgerock.opendj.server.config.server.LDAPConnectionHandlerCfg; |
| | | import org.forgerock.opendj.server.config.server.TraditionalWorkQueueCfg; |
| | | import org.forgerock.util.Options; |
| | | import org.glassfish.grizzly.memory.Buffers; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOConnection; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOServerConnection; |
| | | import org.glassfish.grizzly.nio.transport.TCPNIOTransport; |
| | | import org.opends.admin.ads.util.BlindTrustManager; |
| | | import org.opends.server.DirectoryServerTestCase; |
| | | import org.opends.server.TestCaseUtils; |
| | | import org.opends.server.api.ClientConnection; |
| | |
| | | import org.opends.server.api.ServerShutdownListener; |
| | | import org.opends.server.core.DirectoryServer; |
| | | import org.opends.server.extensions.InitializationUtils; |
| | | import org.opends.server.extensions.TraditionalWorkQueue; |
| | | import org.opends.server.tools.LDAPReader; |
| | | import org.opends.server.types.Entry; |
| | | import org.opends.server.types.Operation; |
| | | import org.opends.server.util.TestTimer; |
| | | import org.testng.annotations.BeforeClass; |
| | | import org.testng.annotations.DataProvider; |
| | | import org.testng.annotations.Test; |
| | |
| | | } |
| | | } |
| | | |
| | | @Test |
| | | public void finalizeReleasesTheListeningPortForImmediateRestart() throws Exception |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final LDAPConnectionHandler2 handler = start(configuration(port, true, true, true, 2)); |
| | | try |
| | | { |
| | | handler.finalizeConnectionHandler(STOP_REASON); |
| | | try (ServerSocket replacement = new ServerSocket()) |
| | | { |
| | | replacement.setReuseAddress(true); |
| | | replacement.bind(new InetSocketAddress("127.0.0.1", port)); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | handler.join(TIMEOUT_MS); |
| | | } |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] liveRemovalOperations() |
| | | { |
| | | return new Object[][] { { false }, { true } }; |
| | | } |
| | | |
| | | @Test(dataProvider = "liveRemovalOperations") |
| | | public void liveDisableOrDeleteCompletesWhileTheListenerWaitsForQueueSpace(boolean delete) throws Exception |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final Entry entry = configurationEntry(port, true, true, true, 1); |
| | | final DN dn = entry.getName(); |
| | | final TraditionalWorkQueue queue = (TraditionalWorkQueue) DirectoryServer.getWorkQueue(); |
| | | final TraditionalWorkQueueCfg original = |
| | | (TraditionalWorkQueueCfg) DirectoryServer.getInstance().getServerContext().getRootConfig().getWorkQueue(); |
| | | final CountDownLatch running = new CountDownLatch(1); |
| | | final CountDownLatch releaseWorker = new CountDownLatch(1); |
| | | final Operation active = mock(Operation.class); |
| | | doAnswer(invocation -> { |
| | | running.countDown(); |
| | | releaseWorker.await(); |
| | | return null; |
| | | }).when(active).run(); |
| | | |
| | | final Options tls = Options.defaultOptions() |
| | | .set(SSL_CONTEXT, new SSLContextBuilder().setTrustManager(new BlindTrustManager()).getSSLContext()); |
| | | TestCaseUtils.addEntry(entry); |
| | | try (LDAPConnectionFactory adminFactory = |
| | | new LDAPConnectionFactory("localhost", TestCaseUtils.getServerAdminPort(), tls); |
| | | Connection admin = adminFactory.getConnection(); |
| | | LDAPConnectionFactory targetFactory = new LDAPConnectionFactory("127.0.0.1", port); |
| | | Connection target = targetFactory.getConnection()) |
| | | { |
| | | admin.bind("cn=Directory Manager", "password".toCharArray()); |
| | | final LDAPConnectionHandler2 handler = DirectoryServer.getConnectionHandlers().stream() |
| | | .filter(candidate -> dn.equals(candidate.getComponentEntryDN())) |
| | | .map(LDAPConnectionHandler2.class::cast) |
| | | .findFirst().orElseThrow(); |
| | | final Thread selector = acceptedConnection(handler).getSelectorRunner().getRunnerThread(); |
| | | final TestTimer timer = new TestTimer.Builder().maxSleep(TIMEOUT_MS, MILLISECONDS) |
| | | .sleepTimes(10, MILLISECONDS).toTimer(); |
| | | try |
| | | { |
| | | setWorkQueueCapacity(queue, 2); |
| | | queue.submitOperation(active); |
| | | assertTrue(running.await(TIMEOUT_MS, MILLISECONDS), "the worker did not start the active operation"); |
| | | |
| | | final LdapPromise<Result> change = delete ? admin.deleteAsync(newDeleteRequest(dn)) |
| | | : admin.modifyAsync(newModifyRequest(dn).addModification(REPLACE, "ds-cfg-enabled", "false")); |
| | | timer.repeatUntilSuccess(() -> assertEquals(queue.size(), 1, "the configuration operation was not queued")); |
| | | queue.submitOperation(mock(Operation.class)); |
| | | // The second operation keeps the queue full even after the worker takes the configuration operation. |
| | | setWorkQueueCapacity(queue, 1); |
| | | final LdapPromise<?> read = target.readEntryAsync(DN.rootDN(), singletonList("objectClass")); |
| | | timer.repeatUntilSuccess(() -> assertTrue(selector.getState() == Thread.State.WAITING |
| | | && stream(selector.getStackTrace()).anyMatch(frame -> |
| | | frame.getClassName().equals(TraditionalWorkQueue.class.getName()) |
| | | && frame.getMethodName().equals("submitOperation")), "the selector did not block in the queue")); |
| | | |
| | | releaseWorker.countDown(); |
| | | assertTrue(change.getOrThrow(TIMEOUT_MS, MILLISECONDS).isSuccess()); |
| | | assertSavedConfiguration(dn, delete); |
| | | assertNotNull(admin.readEntryAsync(DN.rootDN(), singletonList("objectClass")) |
| | | .getOrThrow(TIMEOUT_MS, MILLISECONDS), "the administrative connection no longer serves requests"); |
| | | assertNotNull(read.getOrThrow(TIMEOUT_MS, MILLISECONDS), "the established connection did not resume"); |
| | | |
| | | handler.join(TIMEOUT_MS); |
| | | assertFalse(handler.isAlive(), "the disabled or deleted handler did not finish closing"); |
| | | try (ServerSocket replacement = new ServerSocket()) |
| | | { |
| | | replacement.setReuseAddress(true); |
| | | replacement.bind(new InetSocketAddress("127.0.0.1", port)); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | releaseWorker.countDown(); |
| | | queue.applyConfigurationChange(original); |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | if (DirectoryServer.getEntry(dn) != null) |
| | | { |
| | | TestCaseUtils.deleteEntry(dn); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private static void setWorkQueueCapacity(TraditionalWorkQueue queue, int capacity) |
| | | { |
| | | final TraditionalWorkQueueCfg config = mock(TraditionalWorkQueueCfg.class); |
| | | when(config.getNumWorkerThreads()).thenReturn(1); |
| | | when(config.getMaxWorkQueueCapacity()).thenReturn(capacity); |
| | | queue.applyConfigurationChange(config); |
| | | } |
| | | |
| | | private static void assertSavedConfiguration(DN dn, boolean delete) throws IOException |
| | | { |
| | | try (LDIFEntryReader reader = new LDIFEntryReader(Files.newInputStream(Paths.get(DirectoryServer.getConfigFile())))) |
| | | { |
| | | while (reader.hasNext()) |
| | | { |
| | | final org.forgerock.opendj.ldap.Entry saved = reader.readEntry(); |
| | | if (dn.equals(saved.getName())) |
| | | { |
| | | assertFalse(delete, "the deleted handler is still in config.ldif"); |
| | | assertEquals(saved.parseAttribute("ds-cfg-enabled").asString(), "false"); |
| | | return; |
| | | } |
| | | } |
| | | } |
| | | assertTrue(delete, "the disabled handler is missing from config.ldif"); |
| | | } |
| | | |
| | | @DataProvider |
| | | public Object[][] reuseAddress() |
| | | { |
| | |
| | | start(configuration(freePort(reuseAddress), true, true, reuseAddress, 2)); |
| | | try |
| | | { |
| | | final Collection<?> serverConnections = (Collection<?>) field(field(handler, "listener"), "impl", "serverConnections"); |
| | | final Collection<?> serverConnections = (Collection<?>) field(field(handler, "listener"), "serverConnections"); |
| | | assertFalse(serverConnections.isEmpty(), "the handler does not listen"); |
| | | for (Object serverConnection : serverConnections) |
| | | { |
| | |
| | | |
| | | /** |
| | | * The server shutting down, here for an in-core restart, ends the connections of a handler that is still listening |
| | | * with a notice of disconnection. The handler stops its listener on its own thread, which may wake before or after |
| | | * the next server instance is current: {@link #drainEndsTheConnectionsWhenTheServerOfItsHandlerIsShuttingDown()} |
| | | * covers the latter. |
| | | * with a notice of disconnection. The handler stops listening on its own thread and then drains the transport. |
| | | * {@link #drainEndsTheConnectionsWhenTheServerOfItsHandlerIsShuttingDown()} covers a drain against a previous server |
| | | * instance. |
| | | */ |
| | | @Test |
| | | public void serverRestartEndsTheConnectionsOfAListeningHandler() throws Exception |
| | |
| | | private static LDAPConnectionHandlerCfg configuration(int port, boolean keepAlive, boolean noDelay, |
| | | boolean reuseAddress, Integer numRequestHandlers) throws Exception |
| | | { |
| | | return InitializationUtils.getConfiguration(LDAPConnectionHandlerCfgDefn.getInstance(), |
| | | configurationEntry(port, keepAlive, noDelay, reuseAddress, numRequestHandlers)); |
| | | } |
| | | |
| | | private static Entry configurationEntry(int port, boolean keepAlive, boolean noDelay, |
| | | boolean reuseAddress, Integer numRequestHandlers) throws Exception |
| | | { |
| | | final List<String> lines = new ArrayList<>(); |
| | | lines.add("dn: cn=Transport Test Handler,cn=Connection Handlers,cn=config"); |
| | | lines.add("objectClass: top"); |
| | |
| | | { |
| | | lines.add("ds-cfg-num-request-handlers: " + numRequestHandlers); |
| | | } |
| | | final Entry entry = TestCaseUtils.makeEntry(lines.toArray(new String[0])); |
| | | return InitializationUtils.getConfiguration(LDAPConnectionHandlerCfgDefn.getInstance(), entry); |
| | | return TestCaseUtils.makeEntry(lines.toArray(new String[0])); |
| | | } |
| | | |
| | | private static LDAPConnectionHandler2 start(LDAPConnectionHandlerCfg config) throws Exception |
| | |
| | | import java.util.concurrent.CompletableFuture; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Future; |
| | | import java.util.concurrent.FutureTask; |
| | | import java.util.concurrent.RunnableScheduledFuture; |
| | | import java.util.concurrent.ThreadPoolExecutor; |
| | | import java.util.concurrent.TimeUnit; |
| | |
| | | import org.opends.server.tools.LDAPReader; |
| | | import org.opends.server.types.DisconnectReason; |
| | | import org.opends.server.types.Entry; |
| | | import org.testng.SkipException; |
| | | import org.testng.annotations.BeforeClass; |
| | | import org.testng.annotations.Test; |
| | | |
| | |
| | | } |
| | | |
| | | /** |
| | | * A connection accepted after the handler is finalized, before its listener stops, is still released when it |
| | | * closes: the handler has no finalizer left to time it. |
| | | * A connection that finishes accept after the connection finalizer shuts down still gives back its place when it |
| | | * closes. |
| | | */ |
| | | @Test |
| | | public void connectionAcceptedWhileTheHandlerIsFinalizedIsReleasedWhenItCloses() throws Exception |
| | | public void connectionAcceptedDuringFinalizationGivesBackItsPlaceWhenItCloses() throws Exception |
| | | { |
| | | for (int attempt = 0; attempt < 5; attempt++) |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final LDAPConnectionHandler2 handler = |
| | | start(configuration(port, "ds-cfg-max-client-connections-per-address: 2")); |
| | | final ExecutorService finalizer = finalizer(handler); |
| | | final FutureTask<Void> shutdown = new FutureTask<>(() -> handler.finalizeConnectionHandler(STOP_REASON), null); |
| | | final CompletableFuture<Void> acceptStarted = new CompletableFuture<>(); |
| | | final CompletableFuture<Void> finishAccept = new CompletableFuture<>(); |
| | | final PostConnectPlugin plugin = new PostConnectPlugin(handler, connection -> { |
| | | acceptStarted.complete(null); |
| | | finishAccept.join(); |
| | | return PluginResult.PostConnect.continueConnectProcessing(); |
| | | }); |
| | | try (Socket established = new Socket("127.0.0.1", port)) |
| | | { |
| | | final int port = TestCaseUtils.findFreePort(); |
| | | final LDAPConnectionHandler2 handler = start(configuration(port)); |
| | | // Keep the transport draining while the next connection is still in its post-connect plugin. |
| | | bindAnonymously(established); |
| | | DirectoryServer.registerInternalPlugin(plugin); |
| | | try |
| | | { |
| | | // The listener stops only when run() next wakes up, up to a second later. |
| | | handler.finalizeConnectionHandler(STOP_REASON); |
| | | try (Socket client = new Socket("127.0.0.1", port)) |
| | | { |
| | | if (!awaitClientConnectionsQuietly(handler, 1)) |
| | | { |
| | | continue; |
| | | } |
| | | acceptStarted.get(TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | new Thread(shutdown, "Finalize limits test handler").start(); |
| | | assertTrue(finalizer.awaitTermination(TIMEOUT_MS, TimeUnit.MILLISECONDS), |
| | | "the connection finalizer did not shut down while accept was in flight"); |
| | | finishAccept.complete(null); |
| | | shutdown.get(TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | |
| | | bindAnonymously(client); |
| | | awaitClientConnections(handler, 2); |
| | | awaitPlacesHeld(handler, 2); |
| | | } |
| | | catch (IOException listenerAlreadyStopped) |
| | | { |
| | | continue; |
| | | } |
| | | awaitClientConnections(handler, 0); |
| | | return; |
| | | awaitClientConnections(handler, 1); |
| | | awaitPlacesHeld(handler, 1); |
| | | } |
| | | finally |
| | | { |
| | | handler.join(TIMEOUT_MS); |
| | | finishAccept.complete(null); |
| | | DirectoryServer.deregisterInternalPlugin(plugin); |
| | | } |
| | | } |
| | | throw new SkipException("the listener stopped before a connection could reach the finalized handler"); |
| | | finally |
| | | { |
| | | // Finalize once, including if setup failed before the shutdown thread was started. |
| | | shutdown.run(); |
| | | shutdown.get(TIMEOUT_MS, TimeUnit.MILLISECONDS); |
| | | handler.join(TIMEOUT_MS); |
| | | assertFalse(handler.isAlive(), "the connection handler thread is still running"); |
| | | } |
| | | awaitClientConnections(handler, 0); |
| | | awaitPlacesHeld(handler, 0); |
| | | } |
| | | |
| | | /** |
| | |
| | | assertEquals(client.getInputStream().read(), -1, "the connection stayed open after the notice"); |
| | | } |
| | | |
| | | private static boolean awaitClientConnectionsQuietly(LDAPConnectionHandler2 handler, int expected) |
| | | throws Exception |
| | | { |
| | | final long deadline = System.currentTimeMillis() + TIMEOUT_MS; |
| | | while (handler.getClientConnections().size() != expected) |
| | | { |
| | | if (System.currentTimeMillis() >= deadline) |
| | | { |
| | | return false; |
| | | } |
| | | Thread.sleep(50); |
| | | } |
| | | return true; |
| | | } |
| | | |
| | | private static void awaitClientConnections(LDAPConnectionHandler2 handler, int expected) throws Exception |
| | | { |
| | | final long deadline = System.currentTimeMillis() + TIMEOUT_MS; |
| | |
| | | import java.util.Set; |
| | | import java.util.StringTokenizer; |
| | | import java.util.UUID; |
| | | import java.util.concurrent.CountDownLatch; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | import org.assertj.core.api.Assertions; |
| | | import org.assertj.core.data.MapEntry; |
| | |
| | | private final int RS_SERVER_ID = 90; |
| | | /** Sleep time of the RS, before sending an ack. */ |
| | | private static final long NO_TIMEOUT_RS_SLEEP_TIME = 2000; |
| | | /** Read timeout for the final check that a replay did not send an ack. */ |
| | | private static final int NO_ACK_READ_TIMEOUT = 5000; |
| | | private final String testName = getClass().getSimpleName(); |
| | | |
| | | /** |
| | |
| | | * Signal that the current scenario the RS must execute reached the point |
| | | * where the main code can perform test assertion. |
| | | */ |
| | | private boolean scenarioExecuted; |
| | | private final CountDownLatch scenarioExecuted = new CountDownLatch(1); |
| | | private long ackSendStartedNanos; |
| | | |
| | | private CSNGenerator gen; |
| | | private String testcase; |
| | |
| | | return handshakeOk; |
| | | } |
| | | |
| | | /** |
| | | * Tells the main code that the fake RS executed enough of the expected |
| | | * scenario and can perform test assertion. |
| | | */ |
| | | public boolean isScenarioExecuted() |
| | | /** Waits until the fake RS has completed the part of the scenario under test. */ |
| | | private void awaitScenarioExecuted() throws InterruptedException |
| | | { |
| | | return scenarioExecuted; |
| | | assertTrue(scenarioExecuted.await(10, TimeUnit.SECONDS), |
| | | testcase + ": timed out waiting for the fake RS to complete the scenario"); |
| | | } |
| | | |
| | | /** Checks the add timing before waiting for the fake RS to finish publishing the ACK. */ |
| | | private void assertAddWaitedForAck(long startTime, int timeout) throws InterruptedException |
| | | { |
| | | final long addReturnedNanos = System.nanoTime(); |
| | | assertBlockedForLessThanTimeout(startTime, timeout); |
| | | awaitScenarioExecuted(); |
| | | assertTrue(addReturnedNanos - ackSendStartedNanos >= 0, "add returned before the fake RS sent the ACK"); |
| | | } |
| | | |
| | | /** Handle client connection then call code specific to configured test. */ |
| | |
| | | */ |
| | | private AckMsg sendAssuredAddMsg(Entry entry, String parentUid) throws Exception |
| | | { |
| | | publishAssuredAddMsg(entry, parentUid); |
| | | return waitForSpecificMsg(session, AckMsg.class); |
| | | } |
| | | |
| | | private void assertNoAckForAssuredAdd(Entry entry, String parentUid) throws Exception |
| | | { |
| | | publishAssuredAddMsg(entry, parentUid); |
| | | // Confirm the DS replayed the add before checking whether it acknowledged it. |
| | | assertNotNull(getEntry(entry.getName(), NO_ACK_READ_TIMEOUT, true)); |
| | | |
| | | // This is the session's last read before the test closes it. |
| | | session.setSoTimeout(NO_ACK_READ_TIMEOUT); |
| | | assertThrows(SocketTimeoutException.class, () -> waitForSpecificMsg(session, AckMsg.class)); |
| | | } |
| | | |
| | | private void publishAssuredAddMsg(Entry entry, String parentUid) throws Exception |
| | | { |
| | | AddMsg addMsg = new AddMsg( |
| | | gen.newCSN(), entry.getName(), UUID.randomUUID().toString(), |
| | | parentUid, entry.getObjectClassAttribute(), entry.getAllAttributes(), null); |
| | |
| | | addMsg.setAssuredMode(assuredMode); |
| | | addMsg.setSafeDataLevel(safeDataLevel); |
| | | session.publish(addMsg); |
| | | |
| | | return waitForSpecificMsg(session, AckMsg.class); |
| | | } |
| | | |
| | | /** Read the coming update and check parameters are not assured. */ |
| | |
| | | { |
| | | checkAssuredParametersOnReceivedUpdateMsg(); |
| | | |
| | | scenarioExecuted = true; |
| | | scenarioExecuted.countDown(); |
| | | } |
| | | |
| | | /** Read the coming update and make the client time out by not sending back the ack. */ |
| | |
| | | { |
| | | checkAssuredParametersOnReceivedUpdateMsg(); |
| | | |
| | | scenarioExecuted = true; |
| | | scenarioExecuted.countDown(); |
| | | |
| | | // We do not send back an ack and the client code is expected to be |
| | | // blocked at least for the programmed timeout time. |
| | |
| | | |
| | | // Send the ack without errors |
| | | AckMsg ackMsg = new AckMsg(updateMsg.getCSN()); |
| | | ackSendStartedNanos = System.nanoTime(); |
| | | session.publish(ackMsg); |
| | | |
| | | scenarioExecuted = true; |
| | | scenarioExecuted.countDown(); |
| | | } |
| | | |
| | | /** |
| | |
| | | updateMsg = checkAssuredParametersOnReceivedUpdateMsg(); |
| | | |
| | | // let timeout occur |
| | | scenarioExecuted = true; |
| | | scenarioExecuted.countDown(); |
| | | } |
| | | |
| | | /** Read the coming safe data mode updates and send back acks with errors. */ |
| | |
| | | updateMsg = checkAssuredParametersOnReceivedUpdateMsg(); |
| | | |
| | | // let timeout occur |
| | | scenarioExecuted = true; |
| | | scenarioExecuted.countDown(); |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | long endTime = System.currentTimeMillis(); |
| | | |
| | | waitForScenarioExecutedOnRs(testcase, replicationServer); |
| | | replicationServer.awaitScenarioExecuted(); |
| | | |
| | | if (rsGroupId == 1) |
| | | { |
| | | // RS has same group id as DS |
| | | assertBlockedLongerThanTimeout(startTime, endTime, TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | |
| | | // Check monitoring values |
| | | Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked |
| | |
| | | } |
| | | long endTime = System.currentTimeMillis(); |
| | | |
| | | waitForScenarioExecutedOnRs(testcase, replicationServer); |
| | | replicationServer.awaitScenarioExecuted(); |
| | | |
| | | if (rsGroupId == 1) |
| | | { |
| | | assertBlockedLongerThanTimeout(startTime, endTime, TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | |
| | | // Check monitoring values |
| | | Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked |
| | |
| | | "objectClass: organizationalUnit"); |
| | | |
| | | // Wait for entry received by RS |
| | | waitForScenarioExecutedOnRs(testcase, replicationServer); |
| | | replicationServer.awaitScenarioExecuted(); |
| | | |
| | | // No more test to do here |
| | | } finally |
| | |
| | | } while (!rs.isHandshakeOk()); |
| | | } |
| | | |
| | | /** |
| | | * Wait for the scenario to be executed by the fake replication server or |
| | | * times out with error after some seconds. |
| | | */ |
| | | private void waitForScenarioExecutedOnRs(String testCase, FakeReplicationServer rs) throws Exception |
| | | { |
| | | int nsec = -1; |
| | | do |
| | | { |
| | | nsec++; |
| | | if (nsec == 10) |
| | | { |
| | | fail(testCase + ": timeout waiting for scenario to be exectued on fake RS after " + nsec + " seconds."); |
| | | } |
| | | Thread.sleep(1000); |
| | | } while (!rs.isScenarioExecuted()); |
| | | } |
| | | |
| | | private void endTest(String testcase) throws Exception |
| | | { |
| | | debugInfo("Ending test " + testcase); |
| | |
| | | "objectClass: top", |
| | | "objectClass: organizationalUnit"); |
| | | |
| | | assertBlockedForLessThanTimeout(startTime, TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | replicationServer.assertAddWaitedForAck(startTime, TIMEOUT); |
| | | |
| | | // Check monitoring values |
| | | Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked |
| | |
| | | "objectClass: top", |
| | | "objectClass: organizationalUnit"); |
| | | |
| | | assertBlockedForLessThanTimeout(startTime, TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | replicationServer.assertAddWaitedForAck(startTime, TIMEOUT); |
| | | |
| | | // Check monitoring values |
| | | Thread.sleep(1000); // Sleep a while as counters are updated just after sending thread is unblocked |
| | |
| | | // Wait for connection of domain to RS |
| | | waitForConnectionToRs(testcase, replicationServer); |
| | | |
| | | /* Send an update from the RS and get the ack */ |
| | | |
| | | // Make the RS send an assured add message |
| | | Entry entry = makeEntry( |
| | | "dn: ou=assured-sr-reply-entry," + SAFE_READ_DN, |
| | | "dn: ou=assured-sr-reply-entry-" + rsGroupId + "," + SAFE_READ_DN, |
| | | "objectClass: top", |
| | | "objectClass: organizationalUnit"); |
| | | String parentUid = getEntryUUID(DN.valueOf(SAFE_READ_DN)); |
| | | |
| | | try { |
| | | AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid); |
| | | |
| | | if (rsGroupId == 2) |
| | | { |
| | | fail("Should only go here for RS with same group id as DS"); |
| | | } |
| | | |
| | | // Ack received, replay has occurred |
| | | assertNotNull(DirectoryServer.getEntry(entry.getName())); |
| | | |
| | | // Check that DS replied an ack without errors anyway |
| | | assertFalse(ackMsg.hasTimeout()); |
| | | assertFalse(ackMsg.hasReplayError()); |
| | | assertFalse(ackMsg.hasWrongStatus()); |
| | | assertEquals(ackMsg.getFailedServers().size(), 0); |
| | | |
| | | // Check for monitoring data |
| | | DN baseDN = DN.valueOf(SAFE_READ_DN); |
| | | new MonitorAssertions(baseDN) |
| | | .assertValue("assured-sr-received-updates", 1) |
| | | .assertValue("assured-sr-received-updates-acked", 1) |
| | | .assertRemainingValuesAreZero(); |
| | | assertNoServerErrors(baseDN); |
| | | } |
| | | catch (SocketTimeoutException e) |
| | | if (rsGroupId == 2) |
| | | { |
| | | // Expected |
| | | if (rsGroupId == 1) |
| | | { |
| | | fail("Should only go here for RS with group id different from DS one"); |
| | | } |
| | | |
| | | replicationServer.assertNoAckForAssuredAdd(entry, parentUid); |
| | | return; |
| | | } |
| | | |
| | | AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid); |
| | | |
| | | // Ack received, replay has occurred |
| | | assertNotNull(DirectoryServer.getEntry(entry.getName())); |
| | | |
| | | // Check that DS replied an ack without errors |
| | | assertFalse(ackMsg.hasTimeout()); |
| | | assertFalse(ackMsg.hasReplayError()); |
| | | assertFalse(ackMsg.hasWrongStatus()); |
| | | assertEquals(ackMsg.getFailedServers().size(), 0); |
| | | |
| | | // Check for monitoring data |
| | | DN baseDN = DN.valueOf(SAFE_READ_DN); |
| | | new MonitorAssertions(baseDN) |
| | | .assertValue("assured-sr-received-updates", 1) |
| | | .assertValue("assured-sr-received-updates-acked", 1) |
| | | .assertRemainingValuesAreZero(); |
| | | assertNoServerErrors(baseDN); |
| | | } finally |
| | | { |
| | | endTest(testcase); |
| | |
| | | |
| | | /** |
| | | * Tests that a DS receiving an update from a RS in safe data mode does not |
| | | * send back and ack (only safe read is taken into account in DS replay). |
| | | * send back an ack (only safe read is taken into account in DS replay). |
| | | */ |
| | | @Test(dataProvider = "rsGroupIdProvider") |
| | | public void testSafeDataModeReply(byte rsGroupId) throws Exception |
| | |
| | | // Wait for connection of domain to RS |
| | | waitForConnectionToRs(testcase, replicationServer); |
| | | |
| | | // Make the RS send an assured add message: we expect a read timeout as |
| | | // safe data should be ignored by DS |
| | | Entry entry = makeEntry( |
| | | "dn: ou=assured-sd-reply-entry," + SAFE_DATA_DN, |
| | | "dn: ou=assured-sd-reply-entry-" + rsGroupId + "," + SAFE_DATA_DN, |
| | | "objectClass: top", |
| | | "objectClass: organizationalUnit"); |
| | | String parentUid = getEntryUUID(DN.valueOf(SAFE_DATA_DN)); |
| | | |
| | | AckMsg ackMsg = replicationServer.sendAssuredAddMsg(entry, parentUid); |
| | | fail("DS should not reply an ack in safe data mode, however, it replied: " + ackMsg); |
| | | } |
| | | catch (SocketTimeoutException expected) |
| | | { |
| | | return; |
| | | replicationServer.assertNoAckForAssuredAdd(entry, parentUid); |
| | | } |
| | | finally |
| | | { |
| | |
| | | "objectClass: organizationalUnit"); |
| | | |
| | | assertBlockedLongerThanTimeout(startTime, System.currentTimeMillis(), TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | replicationServer.awaitScenarioExecuted(); |
| | | |
| | | // Check monitoring values |
| | | // No ack should have comen back, so timeout incremented (flag and error for rs) |
| | |
| | | "objectClass: organizationalUnit"); |
| | | |
| | | assertBlockedLongerThanTimeout(startTime, System.currentTimeMillis(), TIMEOUT); |
| | | assertTrue(replicationServer.isScenarioExecuted()); |
| | | replicationServer.awaitScenarioExecuted(); |
| | | |
| | | // Check monitoring values |
| | | // No ack should have comen back, so timeout incremented (flag and error for rs) |
| | |
| | | |
| | | // The session started again recovers them, and the first round of its recovery fails, with a |
| | | // change done meanwhile: the recovery keeps it, and the next one publishes it. |
| | | final CountDownLatch changeDone = new CountDownLatch(1); |
| | | rd1.setMissingChangesSearchHook(onTheFirstSearch(search -> |
| | | { |
| | | unchecked(() -> |
| | | { |
| | | replace(dnA, "displayName", "while the failing round searches"); |
| | | done.add(rd1.getLastLocalChange()); |
| | | changeDone.countDown(); |
| | | }).run(); |
| | | failure.accept(search); |
| | | })); |
| | | rd1.disable(); |
| | | rd1.enable(); |
| | | |
| | | assertTrue(changeDone.await(30, SECONDS), "the publisher recorded the third change"); |
| | | final List<CSN> expected = List.copyOf(done); |
| | | new TestTimer.Builder() |
| | | .maxSleep(30, SECONDS) |
| | | .sleepTimes(100, MILLISECONDS) |
| | | .toTimer() |
| | | .repeatUntilSuccess(() -> assertThat(changelogAfter(rs, baseDN, rsMaxCSN)) |
| | | .as("the changes the replication server holds after the ones it had") |
| | | .isEqualTo(done)); |
| | | .isEqualTo(expected)); |
| | | waitUntilTheRecoveryIsOver(rd1); |
| | | replace(dnA, "description", "once the recovery is over"); |
| | | assertInTheChangelog(rs, baseDN, rd1.getLastLocalChange()); |
| | |
| | | final DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | ReplicationServer rs = createReplicationServer(); |
| | | ReplicationServer second = null; |
| | | LDAPReplicationDomain rd1 = createReplicationDomain(serverId); |
| | | try |
| | | { |
| | |
| | | waitUntilTheStateIsSaved(baseDN, rsMaxCSN); |
| | | final List<Entry> backup = newArrayList(DirectoryServer.getEntry(baseDN).duplicate(false), |
| | | DirectoryServer.getEntry(dnA).duplicate(false), DirectoryServer.getEntry(dnB).duplicate(false)); |
| | | |
| | | // Only the second replication server receives the delete. The first stays at the backup. |
| | | final int secondPort = TestCaseUtils.findFreePort(); |
| | | second = createIsolatedReplicationServer(secondPort, "HistoricalCsnOrderingSecond", SECOND_RS_ID); |
| | | connectTo(rd1, towards(secondPort), SECOND_RS_ID); |
| | | TestCaseUtils.deleteEntry(dnB); |
| | | assertInTheChangelog(rs, baseDN, rd1.getLastLocalChange()); |
| | | assertInTheChangelog(second, baseDN, rd1.getLastLocalChange()); |
| | | |
| | | // The data is restored while the domain is disabled, as it was before the delete. |
| | | rd1.disable(); |
| | | restore(backup); |
| | | assertEquals(rd1.applyConfigurationChange(domainConfiguration(serverId, replServers)).getResultCode(), |
| | | ResultCode.SUCCESS); |
| | | rd1.enable(); |
| | | assertEquals(rd1.getRsServerId(), FIRST_RS_ID); |
| | | waitUntilTheRecoveryIsOver(rd1); |
| | | assertNotNull(DirectoryServer.getEntry(dnB), "the entry is back"); |
| | | |
| | | // A replication server which misses the changes after the backup: its recovery publishes the |
| | | // change done since, and not the delete. |
| | | replace(dnA, "description", "once the data was restored"); |
| | | final CSN afterTheRestore = rd1.getLastLocalChange(); |
| | | assertInTheChangelog(rs, baseDN, afterTheRestore); |
| | | assertThat(changelogAfter(rs, baseDN, rsMaxCSN)).containsExactly(afterTheRestore); |
| | | |
| | | startRecovery(rd1); |
| | | final List<ReplicationMsg> published = new ArrayList<>(); |
| | | assertTrue(rd1.buildAndPublishMissingChanges(rsMaxCSN, new TestBroker(published))); |
| | |
| | | finally |
| | | { |
| | | MultimasterReplication.deleteDomain(baseDN); |
| | | remove(rs); |
| | | remove(rs, second); |
| | | } |
| | | } |
| | | |
| | |
| | | * |
| | | * Copyright 2008-2010 Sun Microsystems, Inc. |
| | | * Portions Copyright 2011-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.plugin; |
| | | |
| | |
| | | import org.opends.server.types.Entry; |
| | | import org.opends.server.types.Modification; |
| | | import org.opends.server.types.Operation; |
| | | import org.opends.server.types.SearchResultEntry; |
| | | import org.opends.server.util.TestTimer; |
| | | import org.opends.server.util.TestTimer.CallableVoid; |
| | | import org.testng.annotations.BeforeClass; |
| | |
| | | /** |
| | | * Test the task that purges the replication historical stored in the user |
| | | * entry. |
| | | * Steps : |
| | | * - creates entry containing historical |
| | | * - wait for the purge delay |
| | | * - launch the purge task |
| | | * - verify that all historical has been purged |
| | | * Replay changes older than the configured purge delay, then verify |
| | | * that the scheduled task purges their history in one run. |
| | | * |
| | | * TODO: another test should be written that configures the task no NOT have |
| | | * the time to purge everything in 1 run .. and thus to relaunch it to finish |
| | |
| | | @Test(enabled=true) |
| | | public void testRecurringPurgeIn1Run() throws Exception |
| | | { |
| | | TestCaseUtils.initializeTestBackend(true); |
| | | int entryCount = 10; |
| | | addEntriesWithHistorical(1, entryCount); |
| | | addEntriesWithHistorical(entryCount); |
| | | |
| | | // set the purge delay to 1 minute |
| | | // FIXME could we change this setting to also accept seconds? |
| | | // This way this test would not take one minute to run |
| | | // (and it could also fail less often in jenkins). |
| | | // Make the stored history eligible for the purge task. |
| | | TestCaseUtils.dsconfig( |
| | | "set-replication-domain-prop", |
| | | "--provider-name","Multimaster Synchronization", |
| | | "--domain-name", testName, |
| | | "--set","conflicts-historical-purge-delay:1m"); |
| | | |
| | | // Let's go past the purge delay |
| | | Thread.sleep(90 * 1000); |
| | | |
| | | // launch the purge |
| | | final int maxWaitTimeInSeconds = 120; |
| | | Entry purgeConflictsHistoricalTask = TestCaseUtils.makeEntry( |
| | |
| | | waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE, "(ds-sync-hist=*)", SUCCESS, expectedNumberOfEntries); |
| | | } |
| | | |
| | | /** |
| | | * Add a provided number of generated entries containing historical. |
| | | * @param dnSuffix A suffix to be added to the dn |
| | | * @param entryCnt The number of entries to create |
| | | */ |
| | | private void addEntriesWithHistorical(final int dnSuffix, final int entryCnt) throws Exception |
| | | private void addEntriesWithHistorical(int entryCount) throws Exception |
| | | { |
| | | for (int i=0; i<entryCnt;i++) |
| | | { |
| | | String sdn = "dn: uid=user"+i+dnSuffix+"," + TEST_ROOT_DN_STRING; |
| | | DN baseDN = DN.valueOf(TEST_ROOT_DN_STRING); |
| | | String parentUUID = LDAPReplicationDomain.findEntryUUID(baseDN); |
| | | int serverId = 5; |
| | | long changeTime = System.currentTimeMillis() - MINUTES.toMillis(2); |
| | | List<Modification> modifications = newArrayList( |
| | | new Modification(ModificationType.ADD, Attributes.create("cn;lang-en", "Aaccf Amar", "Aaccf A Amar")), |
| | | new Modification(ModificationType.REPLACE, Attributes.create("givenName", "new given")), |
| | | new Modification(ModificationType.REPLACE, Attributes.create("userPassword", "{CLEAR}new pass")), |
| | | new Modification(ModificationType.REPLACE, Attributes.create("description", "replaced description")), |
| | | new Modification(ModificationType.REPLACE, Attributes.create("sn", "replaced sn")), |
| | | new Modification(ModificationType.REPLACE, Attributes.create("displayName", "2"))); |
| | | |
| | | // Add a test entry. |
| | | TestCaseUtils.addEntry( |
| | | sdn, |
| | | // Replay the aged changes while the domain still has its default retention. |
| | | ReplicationBroker broker = openReplicationSession(baseDN, serverId, 100, replServerPort, 3000); |
| | | try |
| | | { |
| | | int sequence = 0; |
| | | for (int i = 0; i < entryCount; i++) |
| | | { |
| | | String uid = "purge-user-" + i; |
| | | String entryUUID = UUID.randomUUID().toString(); |
| | | Entry entry = TestCaseUtils.makeEntry( |
| | | "dn: uid=" + uid + "," + TEST_ROOT_DN_STRING, |
| | | "objectClass: top", |
| | | "objectClass: person", |
| | | "objectClass: organizationalPerson", |
| | | "objectClass: inetOrgPerson", |
| | | "uid: user"+i, |
| | | "uid: " + uid, |
| | | "cn: Aaccf Amar", |
| | | "sn: Amar", |
| | | "givenName: Aaccf", |
| | | "userPassword: password", |
| | | "userPassword: {CLEAR}password", |
| | | "description: Initial description", |
| | | "displayName: 1" |
| | | ); |
| | | "displayName: 1", |
| | | "entryUUID: " + entryUUID); |
| | | |
| | | // Modify the test entry to give it some history. |
| | | // Test both single and multi-valued attributes. |
| | | CSN addCSN = new CSN(changeTime, sequence++, serverId); |
| | | broker.publish(new AddMsg(addCSN, entry.getName(), entryUUID, parentUUID, |
| | | entry.getObjectClasses(), entry.getUserAttributes(), entry.getOperationalAttributes())); |
| | | } |
| | | |
| | | String path = TestCaseUtils.createTempFile( |
| | | sdn, |
| | | "changetype: modify", |
| | | "add: cn;lang-en", |
| | | "cn;lang-en: Aaccf Amar", |
| | | "cn;lang-en: Aaccf A Amar", |
| | | "-", |
| | | "replace: givenName", |
| | | "givenName: new given", |
| | | "-", |
| | | "replace: userPassword", |
| | | "userPassword: new pass", |
| | | "-", |
| | | "replace: description", |
| | | "description: replaced description", |
| | | "-", |
| | | "replace: sn", |
| | | "sn: replaced sn", |
| | | "-", |
| | | "add: displayName", |
| | | "displayName: 2", |
| | | "-", |
| | | "delete: displayName", |
| | | "displayName: 1", |
| | | "-" |
| | | ); |
| | | |
| | | String[] args = |
| | | for (SearchResultEntry entry : waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE, |
| | | "(&(ds-sync-hist=*)(displayName=1))", SUCCESS, entryCount).getSearchEntries()) |
| | | { |
| | | "-h", "127.0.0.1", |
| | | "-p", String.valueOf(TestCaseUtils.getServerLdapPort()), |
| | | "-D", "cn=Directory Manager", |
| | | "-w", "password", |
| | | "-f", path |
| | | }; |
| | | CSN modifyCSN = new CSN(changeTime, sequence++, serverId); |
| | | broker.publish(new ModifyMsg(modifyCSN, entry.getName(), modifications, EntryHistorical.getEntryUUID(entry))); |
| | | } |
| | | |
| | | ldapmodify(args); |
| | | |
| | | args[9] = TestCaseUtils.createTempFile( |
| | | sdn, |
| | | "changetype: modify", |
| | | "replace: displayName", |
| | | "displayName: 2", |
| | | "-" |
| | | ); |
| | | |
| | | ldapmodify(args); |
| | | for (SearchResultEntry entry : waitForSearchResult(TEST_ROOT_DN_STRING, WHOLE_SUBTREE, |
| | | "(&(ds-sync-hist=*)(displayName=2))", SUCCESS, entryCount).getSearchEntries()) |
| | | { |
| | | Attribute history = EntryHistorical.getHistoricalAttr(entry).iterator().next(); |
| | | assertTrue(history.size() > 1, "Expected add and modify history for " + entry.getName()); |
| | | } |
| | | } |
| | | |
| | | for (int i = 0; i < entryCnt; i++) |
| | | finally |
| | | { |
| | | DN dn = DN.valueOf("uid=user" + i + dnSuffix + "," + TEST_ROOT_DN_STRING); |
| | | getEntry(dn, 1000, true); |
| | | broker.stop(); |
| | | } |
| | | } |
| | | |
| | |
| | | * (without errors). |
| | | */ |
| | | private static final int MAX_SEND_UPDATE_TIME = 2000; |
| | | /** Read deadline for the fake sender when no ack is expected, including time for an assured timeout ack. */ |
| | | private static final int NO_ACK_READ_TIMEOUT = 5000; |
| | | |
| | | /** Default group id. */ |
| | | private static final int DEFAULT_GID = 1; |
| | |
| | | * Make the RS send an assured message and return the ack message it |
| | | * receives from the RS. |
| | | */ |
| | | public AckMsg sendNewFakeUpdate() throws Exception |
| | | public AckMsg sendNewFakeUpdate(boolean expectAck) throws Exception |
| | | { |
| | | if (!expectAck) |
| | | { |
| | | session.setSoTimeout(NO_ACK_READ_TIMEOUT); |
| | | } |
| | | |
| | | // Create a new delete update message (the simplest to create) |
| | | DeleteMsg delMsg = new DeleteMsg(baseDN, gen.newCSN(), |
| | | UUID.randomUUID().toString()); |
| | |
| | | * Send an assured update using configured assured parameters |
| | | */ |
| | | |
| | | boolean expectAck = sdLevel > 1 && fakeRsGid == DEFAULT_GID |
| | | && fakeRsGenId == DEFAULT_GENID && sendInAssured; |
| | | long startTime = System.currentTimeMillis(); |
| | | AckMsg ackMsg = null; |
| | | boolean timeout = false; |
| | | try |
| | | { |
| | | ackMsg = fakeRs1.sendNewFakeUpdate(); |
| | | ackMsg = fakeRs1.sendNewFakeUpdate(expectAck); |
| | | } catch (SocketTimeoutException e) |
| | | { |
| | | debugInfo("testSafeDataFromRS: timeout waiting for update ack"); |
| | |
| | | /* |
| | | * Now check timeout or not according to test configuration parameters |
| | | */ |
| | | if (sdLevel == 1 || fakeRsGid != DEFAULT_GID |
| | | || fakeRsGenId != DEFAULT_GENID || !sendInAssured ) |
| | | if (!expectAck) |
| | | { |
| | | // Should have timed out (no ack) |
| | | assertTrue(timeout); |
| | |
| | | .as("the warning names the state of the replica and the state of the domain") |
| | | .contains(ownCSN.toString()) |
| | | .contains(csn.toString()); |
| | | assertThat(handler.isFollowing()) |
| | | .as("the replica is served from the queue again once it has been sent the change") |
| | | .isTrue(); |
| | | // The writer can deliver the change before it returns to the in-memory queue. |
| | | waitForFollowing(handler); |
| | | } |
| | | finally |
| | | { |
| | |
| | | * information: "Portions Copyright [year] [name of copyright owner]". |
| | | * |
| | | * Copyright 2014-2016 ForgeRock AS. |
| | | * Portions Copyright 2026 3A Systems, LLC. |
| | | */ |
| | | package org.opends.server.replication.server.changelog.file; |
| | | |
| | |
| | | @SuppressWarnings("javadoc") |
| | | public class BlockLogReaderWriterTest extends DirectoryServerTestCase |
| | | { |
| | | private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit"); |
| | | private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-block-reader-writer"); |
| | | private static final File TEST_FILE = new File(TEST_DIRECTORY, "file"); |
| | | private static final RecordParser<Integer, Integer> RECORD_PARSER = new IntRecordParser(); |
| | | private static final int INT_RECORD_SIZE = 12; |
| | |
| | | @Test(sequential=true) |
| | | public class LogFileTest extends DirectoryServerTestCase |
| | | { |
| | | private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit"); |
| | | private static final File TEST_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-log-file"); |
| | | private static final File TEST_LOG_FILE = new File(TEST_DIRECTORY, Log.HEAD_LOG_FILE_NAME); |
| | | static final StringRecordParser RECORD_PARSER = new StringRecordParser(); |
| | | private static final byte STRING_SEPARATOR = 0; |
| | |
| | | public class LogTest extends DirectoryServerTestCase |
| | | { |
| | | /** Use a directory dedicated to this test class. */ |
| | | private static final File LOG_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-unit"); |
| | | private static final File LOG_DIRECTORY = new File(TestCaseUtils.getUnitTestRootPath(), "changelog-log"); |
| | | |
| | | private static final long NO_TIME_BASED_LOG_ROTATION = 0; |
| | | |
| | |
| | | @Test |
| | | public void testRenameFileNonExistentTarget() throws Exception { |
| | | File src = File.createTempFile("src", null); |
| | | File target = new File(src.getParentFile(), "target"); |
| | | File target = File.createTempFile("target", null); |
| | | try { |
| | | if (target.exists()) { |
| | | target.delete(); |
| | | assertFalse(target.exists()); |
| | | } |
| | | assertTrue(target.delete()); |
| | | StaticUtils.renameFile(src, target); |
| | | assertFalse(src.exists()); |
| | | assertTrue(target.exists()); |
| | |
| | | @Test |
| | | public void testIsSelfConnectionTrueForSelfConnectedSocket() throws Exception |
| | | { |
| | | // find a free port |
| | | final int port; |
| | | try (ServerSocket tmp = new ServerSocket()) |
| | | { |
| | | tmp.bind(new InetSocketAddress("127.0.0.1", 0)); |
| | | port = tmp.getLocalPort(); |
| | | } |
| | | |
| | | // Force the TCP self-connect (simultaneous open) that the kernel can |
| | | // produce spontaneously when connecting to an unbound port from the |
| | | // ephemeral range: bind the local end to the very port being connected. |
| | | try (Socket socket = new Socket()) |
| | | { |
| | | socket.setReuseAddress(true); |
| | | socket.bind(new InetSocketAddress("127.0.0.1", port)); |
| | | socket.bind(new InetSocketAddress("127.0.0.1", 0)); |
| | | try |
| | | { |
| | | socket.connect(new InetSocketAddress("127.0.0.1", port), 2000); |
| | | socket.connect(socket.getLocalSocketAddress(), 2000); |
| | | } |
| | | catch (IOException e) |
| | | { |
| | |
| | | <product.locales>ca_ES,es,de,fr,ja,ko,pl,zh_CN,zh_TW</product.locales> |
| | | <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
| | | <localized.jars.classifier>i18n</localized.jars.classifier> |
| | | <commons.version>3.2.2</commons.version> |
| | | <commons.version>3.2.3</commons.version> |
| | | <freemarker.version>2.3.35</freemarker.version> |
| | | <metrics-core.version>4.2.30</metrics-core.version> |
| | | <bc.fips.version>2.1.3</bc.fips.version> |