8000 migrate cluster package to new framework by edewit · Pull Request #52133 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
bca31ee
Migrate cluster package to new test framework
edewit Aug 27, 2026
502291a
fixed tests
edewit Aug 27, 2026
bd8057c
Address cluster migration PR review comments
edewit Sep 8, 2026
d049f8a
Fix OAuth2Code constructor after rebase onto main
edewit Sep 8, 2026
dea35f5
Fix testsuite deprecation check by inlining auth session helper
edewit Sep 8, 2026
00b8738
Wire migrated cluster tests into CI and fix cluster failover support
edewit Sep 11, 2026
e8b8f48
Fix cluster test framework compilation and failover readiness
edewit Sep 11, 2026
3a5c581
Remove unused prepareSessionCode helper from OID4VC test
edewit Sep 15, 2026
ecf8c18
Remove migrated cluster package from legacy base-suite matrix
edewit Sep 15, 2026
19f7d3c
Remove migrated packages from legacy base-suite matrix
edewit Sep 16, 2026
34cf1db
Fix cluster node restart reliability in integration tests
edewit Sep 16, 2026
0b866a6
Recreate cluster nodes on failback instead of docker restart
edewit Sep 16, 2026
4e8641c
Configure cluster cache owners from system properties
edewit Sep 16, 2026
f80ea89
Fix cluster session failover and component invalidation tests
edewit Sep 17, 2026
d605ed1
Fix component provider lookup in cluster invalidation tests
edewit Sep 17, 2026
4b695b9
Address cluster migration review feedback and fix build failure
edewit Sep 17, 2026
e259eaa
Increase Clustering IT CI job timeout to 75 minutes
edewit Sep 17, 2026
8607646
Address review feedback on cluster test migration
edewit Nov 24, 2026
3d3a925
Fix Copilot findings on cluster migration
edewit Nov 24, 2026
fd034bd
Expect successful session failover with volatile caches
edewit Dec 2, 2026
512b9c1
Fix stateless cluster tests requiring cache-embedded-cluster-name
edewit Dec 4, 2026
a8dedad
Resolve cluster test components via provider factory
edewit Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
7 changes: 5 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,7 @@ jobs:
name: Clustering IT
needs: build
runs-on: ubuntu-latest
timeout-minutes: 35
timeout-minutes: 75
env:
MAVEN_OPTS: -Xmx1536m
steps:
Expand All @@ -926,9 +926,12 @@ jobs:
name: Integration test setup
uses: ./.github/actions/integration-test-setup

- name: Build tar keycloak-quarkus-dist
run: ./mvnw package -pl quarkus/server/,quarkus/dist/

- name: Run cluster tests
run: |
./mvnw test ${{ env.SUREFIRE_RETRY }} -Pauth-server-cluster-quarkus,db-postgres "-Dwebdriver.chrome.driver=$CHROMEWEBDRIVER/chromedriver" -Dsession.cache.owners=2 -Dtest=**.cluster.** -pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh
KC_TEST_SERVER=cluster KC_TEST_DATABASE=postgres ./mvnw package -f tests/pom.xml -Dtest=ClusterTestSuite -Dsession.cache.owners=2 ${{ env.SUREFIRE_RETRY }} 2>&1 | misc/log/trimmer.sh

- uses: ./.github/actions/upload-flaky-tests
name: Upload flaky tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public void accept(OutputFrame t) {
private final LazyFuture<String> image;

private final Map<MountableFile, String> copyToContainer = new HashMap<>();
private List<String> lastKcArguments;

public DockerKeycloakDistribution(int[] exposedPorts) {
this(exposedPorts, null);
Expand Down Expand Up @@ -154,6 +155,7 @@ public void runKc(List<String> arguments) {
if (keycloakContainer != null) {
throw new IllegalStateException("Stop has not been called");
}
lastKcArguments = List.copyOf(arguments);
try {
this.exitCode = -1;
this.stdout = "";
Expand All @@ -175,7 +177,7 @@ public void runKc(List<String> arguments) {
this.stdout = backupConsumer.stdOut.toUtf8String();
this.stderr = backupConsumer.stdErr.toUtf8String();
try {
cleanupContainer();
cleanupContainer(containerId);
} catch (Exception stopException) {
cause.addSuppressed(stopException);
}
Expand Down Expand Up @@ -225,51 +227,85 @@ public void waitFor(boolean ready, long timeoutMillis) {

@Override
public void stop() {
stop(true);
}

public void stopNode() {
if (keycloakContainer != null) {
stop(true, true);
}
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

public boolean isRunning() {
return keycloakContainer != null && keycloakContainer.isRunning();
}

public void recreateContainer() {
if (lastKcArguments == null) {
throw new IllegalStateException("Container has not been started");
}
if (isRunning()) {
return;
}
try {
if (keycloakContainer != null) {
stop(true, false);
}
runKc(lastKcArguments);
Comment thread
Copilot marked this conversation as resolved.
Resolved
} catch (Exception cause) {
throw new RuntimeException("Failed to recreate the server", cause);
}
}

private void stop(boolean removeContainer) {
stop(removeContainer, false);
}

private void stop(boolean removeContainer, boolean forceKill) {
String containerToCleanup = null;
try {
if (keycloakContainer != null) {
containerId = keycloakContainer.getContainerId();
containerToCleanup = keycloakContainer.getContainerId();
this.stdout = fetchOutputStream();
this.stderr = fetchErrorStream();

// A graceful shutdown will help with cleaning up resources, for example JDBC_PING table entries.
// Shutdown is fast (less than 100 ms), waiting for a stale JDBC_PING is slow (10+ seconds).
if (keycloakContainer.isRunning()) {
try (KillContainerCmd killContainerCmd = keycloakContainer.getDockerClient().killContainerCmd(keycloakContainer.getContainerId())) {
killContainerCmd.withSignal("TERM").exec();
String signal = forceKill ? "KILL" : "TERM";
try (KillContainerCmd killContainerCmd = keycloakContainer.getDockerClient().killContainerCmd(containerToCleanup)) {
killContainerCmd.withSignal(signal).exec();
}
Awaitility.await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> Assertions.assertFalse(keycloakContainer.isRunning()));
}

keycloakContainer.stop();
if (removeContainer) {
keycloakContainer.stop();
}
this.exitCode = 0;
}
} catch (Exception cause) {
this.exitCode = -1;
throw new RuntimeException("Failed to stop the server", cause);
} finally {
cleanupContainer();
keycloakContainer = null;
if (removeContainer) {
cleanupContainer(containerToCleanup);
keycloakContainer = null;
}
}
}

private void cleanupContainer() {
if (containerId != 10BC8 null) {
private void cleanupContainer(String containerToCleanup) {
if (containerToCleanup != null) {
try {
Runnable reaper = new Runnable() {
@Override
public void run() {
try {
if (containerId == null) {
return;
}
DockerClient dockerClient = DockerClientFactory.lazyClient();
dockerClient.killContainerCmd(containerId).exec();
dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();
} catch (NotFoundException notFound) {
LOGGER.debug("Container is already cleaned up, no additional cleanup required");
} catch (Exception cause) {
throw new RuntimeException("Failed to stop and remove container", cause);
}
final String id = containerToCleanup;
Runnable reaper = () -> {
try {
DockerClient dockerClient = DockerClientFactory.lazyClient();
dockerClient.killContainerCmd(id).exec();
dockerClient.removeContainerCmd(id).withRemoveVolumes(true).withForce(true).exec();
} catch (NotFoundException notFound) {
LOGGER.debug("Container is already cleaned up, no additional cleanup required");
} catch (Exception cause) {
throw new RuntimeException("Failed to stop and remove container", cause);
}
};
parallelReaperExecutor.execute(reaper);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ public void node(int index) {
proxy.origin(origin.port, origin.host);
}

public int getCurrentNodeIndex() {
return currentNodeIndex;
}

public KeycloakUrls nodeUrls(int index) {
return origin(index).urls;
}
Expand All @@ -61,10 +65,31 @@ public int nodeCount() {
return server.clusterSize();
}

public boolean isNodeRunning(int index) {
return server.isNodeRunning(index);
}

public void stopNode(int index) {
server.stopNode(index);
}

public void startNode(int index) {
server.startNode(index);
}

public void nextNode() {
node((currentNodeIndex + 1) % nodeCount());
}

public void refreshNode(int index) {
urls.remove(index);
// Rebind the proxy when the restarted node is currently selected; otherwise it keeps
// targeting the previous mapped port after the container is recreated.
if (currentNodeIndex == index) {
node(index);
}
}

private Origin origin(int index) {
if (index >= server.clusterSize()) {
throw new IllegalArgumentException("Node index out of bounds. Requested nodeIndex: %d, cluster size: %d".formatted(index, server.clusterSize()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
import java.util.function.Supplier;

import org.keycloak.common.Profile;
import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
import org.keycloak.it.utils.DockerKeycloakDistribution;
import org.keycloak.testframework.clustering.LoadBalancer;
import org.keycloak.testframework.infinispan.CacheType;
import org.keycloak.testframework.logging.JBossContainerLogConsumer;

import com.google.common.base.CaseFormat;
import org.jboss.logging.Logger;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.utility.DockerImageName;
Expand Down Expand Up @@ -64,6 +66,7 @@ public ClusteredKeycloakServer(int numServers, String images, long startTimeout,
@Override
public void start(KeycloakServerConfigBuilder configBuilder, boolean tlsEnabled) {
int numServers = containers.length;
configureCacheOwners(configBuilder);

String[] imagePeServer = null;
Supplier<CountdownLatchLoggingConsumer> latchSupplier;
Expand Down Expand Up @@ -137,7 +140,7 @@ private void startContainersWithMixedImage(KeycloakServerConfigBuilder configBui
copyProvidersAndConfigs(container, configBuilder);

configureLogConsumers(container, i, clusterLatch.get());
configureClusterNameIfStatelessEnabled(configBuilder, i);
configureNode(configBuilder, i);
container.runKc(configBuilder.toArgs());
}
}
Expand All @@ -153,7 +156,7 @@ private void startContainersWithSameImage(KeycloakServerConfigBuilder configBuil

copyProvidersAndConfigs(container, configBuilder);
configureLogConsumers(container, i, clusterLatch.get());
configureClusterNameIfStatelessEnabled(configBuilder, i);
configureNode(configBuilder, i);
container.runKc(configBuilder.toArgs());
}
}
Expand Down Expand Up @@ -204,14 +207,83 @@ public int clusterSize() {
return containers.length;
}

public boolean isNodeRunning(int index) {
return containers[index] != null && containers[index].isRunning();
}

public void stopNode(int index) {
containers[index].stopNode();
}

public void startNode(int index) {
if (!containers[index].isRunning()) {
int expectedMembers = expectedClusterMembersAfterStart(index);
var reunionLatch = new CountdownLatchLoggingConsumer(1, String.format(CLUSTER_VIEW_REGEX, expectedMembers));
configureLogConsumers(containers[index], index, reunionLatch);
containers[index].recreateContainer();
try {
long perLatchTimeout = (long) Math.max(1, expectedMembers) * DockerKeycloakDistribution.STARTUP_TIMEOUT_SECONDS;
reunionLatch.await(perLatchTimeout, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException("Node %d failed to rejoin the cluster".formatted(index), e);
}
ReadinessProbe.waitUntilNodeReady(this::getBaseUrl, index, startTimeout);
if (loadBalancer != null) {
loadBalancer.refreshNode(index);
}
}
}

/**
* When several nodes are down, restart them one-by-one: wait only for currently running members
* plus the node being started, not the full configured cluster size.
*/
private int expectedClusterMembersAfterStart(int index) {
if (stateless) {
return 1;
}
int runningOthers = 0;
for (int i = 0; i < containers.length; i++) {
if (i != index && isNodeRunning(i)) {
runningOthers++;
}
}
return runningOthers + 1;
}

public LoadBalancer getLoadBalancer() {
return loadBalancer;
}

private void configureClusterNameIfStatelessEnabled(KeycloakServerConfigBuilder configBuilder, int id) {
if (!stateless) {
return;
private void configureNode(KeycloakServerConfigBuilder configBuilder, int id) {
// SPI option works for mixed-version (pre-26.8) images; first-class option is required for
// validation when feature 'stateless' is enabled on current builds.
configBuilder.spiOption("cache-embedded", "default", "node-name", "node" + (id + 1));
if (stateless) {
configBuilder.option("cache-embedded-cluster-name", "cluster-" + id);
}
configBuilder.option("cache-embedded-cluster-name", "cluster-" + id);
}

private static void configureCacheOwners(KeycloakServerConfigBuilder configBuilder) {
int sessionOwners = Integer.getInteger("session.cache.owners", 1);
int offlineSessionOwners = Integer.getInteger("offline.session.cache.owners", sessionOwners);
int loginFailureOwners = Integer.getInteger("login.failure.cache.owners", sessionOwners);

setCacheOwners(configBuilder, InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, sessionOwners);
setCacheOwners(configBuilder, InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME, sessionOwners);
setCacheOwners(configBuilder, InfinispanConnectionProvider.AUTHENTICATION_SESSIONS_CACHE_NAME, sessionOwners);
setCacheOwners(configBuilder, InfinispanConnectionProvider.OFFLINE_USER_SESSION_CACHE_NAME, offlineSessionOwners);
setCacheOwners(configBuilder, InfinispanConnectionProvider.OFFLINE_CLIENT_SESSION_CACHE_NAME, offlineSessionOwners);
setCacheOwners(configBuilder, InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME, loginFailureOwners);
}

private static void setCacheOwners(KeycloakServerConfigBuilder configBuilder, String cacheName, int owners) {
String option = "spi-cache-embedded--default--"
+ CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, cacheName)
+ "-owners";
configBuilder.option(option, Integer.toString(owners));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ public static void waitUntilReady(KeycloakServer server, long timeout) {
waitUntilReady(index -> server.getBaseUrl(), 1, timeout);
}

public static void waitUntilNodeReady(IntFunction<String> baseUrlFunction, int nodeIndex, long timeout) {
// Use /realms/master rather than /: the welcome page redirects to the advertised hostname
// (the load balancer), which can report success from a different node.
waitUntilReady(baseUrlFunction.apply(nodeIndex) + "/realms/master", createTrustAllSslContext(), timeout);
}

public static void waitUntilReady(IntFunction<String> baseUrlFunction, int clusterSize, long timeout) {
var sslContext = createTrustAllSslContext();
for (int i = 0; i < clusterSize; i++) {
Expand Down
5 changes: 5 additions & 0 deletions test-framework/remote-providers/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@
<artifactId>keycloak-model-infinispan</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-services</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
Expand Down
Loading
Loading
0