Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.keycloak.common.util.Time;
import org.keycloak.connections.jpa.JpaConnectionProviderFactory;
Expand Down Expand Up @@ -78,6 +80,8 @@ public class KEYCLOAK_JDBC_PING2 extends JDBC_PING2 {

private JpaConnectionProviderFactory factory;
private volatile HealthStatus previousHealthStatus = HealthStatus.HEALTHY;
// address of a member that left the view -> time in seconds when it left
private final Map<Address, Long> leftMembers = new ConcurrentHashMap<>();
private volatile int cyclesSinceLastLog = 0;
private volatile Future<?> healthCheckTask;
private volatile Runnable onHealthRestored;
Expand Down Expand Up @@ -154,6 +158,7 @@ protected void insert(Connection connection, PingData data, String clustername)
@Override
protected void handleView(View new_view, View old_view, boolean coord_changed) {
super.handleView(new_view, old_view, coord_changed);
trackLeftMembers(new_view, old_view);
if (coord_changed) {
try {
removeStaleEntries();
Expand All @@ -163,6 +168,25 @@ protected void handleView(View new_view, View old_view, boolean coord_changed) {
}
}

/**
* Remember when members left the view. Their row is allocated to themselves and stays in the table until it is stale,
* and could win the split-brain decision against this node.
* As only a member itself writes its coordinator row, a row updated after the member left shows that it is alive again.
*/
private void trackLeftMembers(View new_view, View old_view) {
leftMembers.keySet().removeIf(new_view::containsMember);
if (old_view == null) {
return;
}
// rows older than the staleness timeout are ignored when reading, so there is no need to remember them
long cutoff = getStalenessCutoff();
leftMembers.values().removeIf(leftAt -> leftAt < cutoff);
long now = Time.currentTime();
for (Address addr : View.diff(old_view, new_view)[1]) {
leftMembers.put(addr, now);
}
}

protected void removeAllNotInCurrentView() {
View local_view = view;
if (local_view == null) {
Expand Down Expand Up @@ -204,14 +228,24 @@ public long nextInterval() {
}

protected List<PingData> readFromDB(String cluster) throws Exception {
return readRowsFromDB(cluster).stream().map(PingRow::data).collect(Collectors.toCollection(LinkedList::new));
}

/**
* A row from the table, with the time of its last update in seconds.
*/
protected record PingRow(PingData data, long lastUpdate) {
}

protected List<PingRow> readRowsFromDB(String cluster) throws Exception {
try(Connection conn=getConnection();
PreparedStatement ps=prepare(conn, select_all_pingdata_sql, TYPE_FORWARD_ONLY, CONCUR_UPDATABLE)) {
ps.setString(1, cluster);
if(log.isTraceEnabled())
log.trace("%s: SQL for reading: %s", local_addr, ps);
try(ResultSet resultSet=ps.executeQuery()) {
reads++;
List<PingData> retval=new LinkedList<>();
List<PingRow> retval=new LinkedList<>();
Map<Address, Set<Address>> members = new HashMap<>();
while(resultSet.next()) {
String uuid=resultSet.getString(1);
Expand All @@ -226,14 +260,14 @@ protected List<PingData> readFromDB(String cluster) throws Exception {
Address addr=Util.addressFromString(uuid);
IpAddress ip_addr=new IpAddress(ip);
PingData data=new PingData(addr, true, name, ip_addr).coord(coord);
retval.add(data);
retval.add(new PingRow(data, last_update));
if (coordinated_by != null) {
Address coordinate_by_address = Util.addressFromString(coordinated_by);
members.computeIfAbsent(coordinate_by_address, address -> new HashSet<>())
.add(addr);
}
}
retval.forEach(a -> a.mbrs(members.get(a.getAddress())));
retval.forEach(r -> r.data().mbrs(members.get(r.data().getAddress())));
return retval;
}
}
Expand Down Expand Up @@ -358,7 +392,7 @@ public void setOnHealthRestored(Runnable onHealthRestored) {
* <ul>
* <li>Reads the data from the database</li>
* <li>If an error occurs fetching the data, it returns {@link HealthStatus#ERROR}</li>
* <li>Filters out non coordinator members</li>
* <li>Filters out non coordinator members, and members that left the view and did not write their row after that</li>
* <li>If no coordinator is found, it return {@link HealthStatus#NO_COORDINATOR}</li>
* <li>If multiple coordinators are found, it compares them and uses the coordinator with the lowest {@link UUID}</li>
* <li>Finally, it compares if the coordinator is the same as the current view coordinator. If so, it returns {@link HealthStatus#HEALTHY}, otherwise {@link HealthStatus#UNHEALTHY}</li>
Expand All @@ -369,9 +403,15 @@ public void setOnHealthRestored(Runnable onHealthRestored) {
*/
public HealthStatus healthStatus() {
try {
HealthStatus status = readFromDB(cluster_name)
HealthStatus status = readRowsFromDB(cluster_name)
.stream()
.filter(PingData::isCoord)
.filter(row -> row.data().isCoord())
// ignore a member that left our view, until it writes its row again
.filter(row -> {
Long leftAt = leftMembers.get(row.data().getAddress());
return leftAt == null || row.lastUpdate() > leftAt;
})
.map(PingRow::data)
.sorted(SPLIT_BRAIN_DECIDER)
.map(PingData::getAddress)
.findFirst()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ public HealthStatus healthStatus() {
}

@Override
protected List<PingData> readFromDB(String cluster) throws Exception {
protected List<PingRow> readRowsFromDB(String cluster) throws Exception {
if (exception != null) {
throw exception;
}
return pingData;
return pingData.stream().map(data -> new PingRow(data, Long.MAX_VALUE)).toList();
}

public void setPingData(List<Address> coordinators) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.PhysicalAddress;
import org.jgroups.View;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.logging.Log;
import org.jgroups.protocols.PingData;
Expand Down Expand Up @@ -247,6 +248,53 @@ public void testClearing() throws Exception {
}
}

@Test
public void testLeftCoordinatorIgnoredUntilItWritesAgain() throws Exception {
JChannel channel = createChannel("0");
try (channel) {
channel.connect("ISPN");
KEYCLOAK_JDBC_PING2_FOR_TESTING jdbcPing = (KEYCLOAK_JDBC_PING2_FOR_TESTING) channel.getProtocolStack().getProtocols().stream().filter(protocol -> protocol instanceof KEYCLOAK_JDBC_PING2).findFirst().orElseThrow(() -> new RuntimeException("Didn't find JDBC_PING"));
jdbcPing.writeAll();
UUID left = UUID.randomUUID();
List<UUID> members = List.of(left, UUID.randomUUID(), UUID.randomUUID());
try (Connection con = jdbcPing.getConnection()) {
// A coordinator of a larger partition, that would win the split-brain decision against this node
for (UUID address : members) {
try (PreparedStatement ps = con.prepareStatement(jdbcPing.getInsertSingleSql())) {
ps.setString(1, Util.addressToString(address));
ps.setString(2, "x");
ps.setString(3, jdbcPing.getClusterName());
ps.setString(4, "127.0.0.1:9999");
ps.setBoolean(5, address.equals(left));
ps.setLong(6, Time.currentTime());
ps.setString(7, Util.addressToString(left));
ps.executeUpdate();
}
}
assertEquals(KEYCLOAK_JDBC_PING2.HealthStatus.UNHEALTHY, jdbcPing.healthStatus());

// The coordinator leaves the view, and is ignored
jdbcPing.handleView(channel.view(), View.create(left, 1, left, channel.getAddress()), true);
assertEquals(KEYCLOAK_JDBC_PING2.HealthStatus.HEALTHY, jdbcPing.healthStatus());

// It writes its row again, so it is alive and counted again
try (PreparedStatement ps = con.prepareStatement("UPDATE jgroups SET last_update = ? WHERE address = ?")) {
ps.setLong(1, Time.currentTime() + 1);
ps.setString(2, Util.addressToString(left));
ps.executeUpdate();
}
assertEquals(KEYCLOAK_JDBC_PING2.HealthStatus.UNHEALTHY, jdbcPing.healthStatus());
} finally {
try (Connection con = jdbcPing.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM jgroups WHERE address = ?")) {
for (UUID address : members) {
ps.setString(1, Util.addressToString(address));
ps.executeUpdate();
}
}
}
}
}

@SuppressWarnings("resource")
protected static JChannel createChannel(String name) throws Exception {
return new JChannel(JdbcPing2Test.PROTOCOL_STACK).name(name);
Expand Down
Loading