8000 Adding staleness concept to JDBC_PING by ahus1 · Pull Request #47971 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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
< 10BC8 td class="blob-code blob-code-addition js-file-line"> members.computeIfAbsent(coordinate_by_address, address -> new HashSet<>())
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,45 @@
package org.keycloak.jgroups.protocol;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.keycloak.common.util.Time;
import org.keycloak.connections.jpa.JpaConnectionProviderFactory;

import org.jgroups.Address;
import org.jgroups.PhysicalAddress;
import org.jgroups.View;
import org.jgroups.annotations.Property;
import org.jgroups.conf.AttributeType;
import org.jgroups.protocols.JDBC_PING2;
import org.jgroups.protocols.PingData;
import org.jgroups.protocols.relay.SiteUUID;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.NameCache;
import org.jgroups.util.UUID;
import org.jgroups.util.Util;

import static java.sql.ResultSet.CONCUR_UPDATABLE;
import static java.sql.ResultSet.TYPE_FORWARD_ONLY;

public class KEYCLOAK_JDBC_PING2 extends JDBC_PING2 {

private JpaConnectionProviderFactory factory;

@Property(description="Staleness timeout in milliseconds. The coordinator will update the entries once 50%-75% of the time has passed.", type= AttributeType.TIME)
protected long staleness_timeout = 60000L;

@Override
protected void loadDriver() {
//no-op, using JpaConnectionProviderFactory
Expand All @@ -51,10 +77,162 @@ protected Connection getConnection() throws SQLException {
}
}

@Override
public void init() throws Exception {
if (!write_data_on_find) {
throw new RuntimeException("Running this without write_data_on_find is not safe");
}
if (!remove_all_data_on_view_change) {
throw new RuntimeException("Running this without remove_all_data_on_view_change is not safe");
}
super.init();
}

protected void insert(Connection connection, PingData data, String clustername) throws SQLException {
lock.lock();
try(PreparedStatement ps=connection.prepareStatement(insert_single_sql)) {
Address address=data.getAddress();
String addr= Util.addressToString(address);
String name=address instanceof SiteUUID ? ((SiteUUID)address).getName() : NameCache.get(address);
PhysicalAddress ip_addr=data.getPhysicalAddr();
String ip=ip_addr.toString();
ps.setString(1, addr);
ps.setString(2, name);
ps.setString(3, clustername);
ps.setString(4, ip);
ps.setBoolean(5, data.isCoord());
ps.setLong(6, Time.currentTime());
ps.setString(7, view != null && view.getCoord() != null ? Util.addressToString(view.getCoord()) : null);
if (log.isTraceEnabled())
log.trace("%s: SQL for insertion: %s", local_addr, ps);
ps.executeUpdate();
log.debug("%s: inserted %s for cluster %s", local_addr, address, clustername);
} finally {
lock.unlock();
}
}

@Override
protected void handleView(View new_view, View old_view, boolean coord_changed) {
super.handleView(new_view, old_view, coord_changed);
if (coord_changed) {
try {
removeStaleEntries();
} catch (Exception e) {
log.error(String.format("%s: failed handling view change", local_addr), e);
}
}
}

protected void removeAllNotInCurrentView() {
View local_view = view;
if (local_view == null) {
return;
}
String cluster_name = getClusterName();
try {
List<PingData> list = readFromDB(getClusterName());
PingData my_data = list.stream().filter(p -> Objects.equals(p.getAddress(), addr())).findFirst().orElse(null);
if (my_data == null || my_data.mbrs() == null) {
return;
}
for (PingData data : list) {
Address addr = data.getAddress();
// Only delete an entry if it is currently allocated to us, and not someone else
if (!local_view.containsMember(addr) && my_data.mbrs().contains(addr)) {
try (var conn = getConnection()) {
addDiscoveryResponseToCaches(addr, data.getLogicalName(), data.getPhysicalAddr());
delete(conn, cluster_name, addr);
}
}
}
} catch (Exception e) {
log.error(String.format("%s: failed reading from the DB", local_addr), e);
}
}

/**
* The infowriter will run on the coordinator only. It will continue to run while this is the coordinator, not only after the view change
*/
protected synchronized void startInfoWriter() {
if(info_writer == null || info_writer.isDone())
info_writer=timer.scheduleWithDynamicInterval(new InfoWriter(info_writer_max_writes_after_view, info_writer_sleep_time) {
@Override
public long nextInterval() {
return is_coord ? (staleness_timeout / 2 + Util.random(sleep_interval / 4)) : 0;
}
});
}

protected List<PingData> readFromDB(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<>();
Map<Address, Set<Address>> members = new HashMap<>();
while(resultSet.next()) {
String uuid=resultSet.getString(1);
String name=resultSet.getString(2);
String ip=resultSet.getString(3);
boolean coord=resultSet.getBoolean(4);
String coordinated_by=resultSet.getString(5);
long last_update=resultSet.getLong(6);
if (last_update < getStalenessCutoff()) {
continue;
}
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);
if (coordinated_by != null) {
Address coordinate_by_address = Util.addressFromString(coordinated_by);
.add(addr);
}
}
retval.forEach(a -> a.mbrs(members.get(a.getAddress())));
return retval;
}
}
}

protected void removeStaleEntries() throws Exception {
try(Connection conn=getConnection();
PreparedStatement ps=prepare(conn, select_all_pingdata_sql, TYPE_FORWARD_ONLY, CONCUR_UPDATABLE)) {
ps.setString(1, getClusterName());
if(log.isTraceEnabled())
log.trace("%s: SQL for reading: %s", local_addr, ps);
try(ResultSet resultSet=ps.executeQuery()) {
reads++;
while(resultSet.next()) {
String uuid=resultSet.getString(1);
long last_update=resultSet.getLong(6);
if (last_update < getStalenessCutoff()) {
Address addr=Util.addressFromString(uuid);
delete(conn, getClusterName(), addr);
}
}
}
}
}

private long getStalenessCutoff() {
return TimeUnit.MILLISECONDS.toSeconds(Time.currentTimeMillis() - staleness_timeout);
}

public void setJpaConnectionProviderFactory(JpaConnectionProviderFactory factory) {
this.factory = Objects.requireNonNull(factory);
}

// Pick the largest partition first, then order by address to allow for a stable result
private final static Comparator<PingData> SPLIT_BRAIN_DECIDER = Comparator
.<PingData, Integer>comparing(p -> p.mbrs() != null ? p.mbrs().size() : 0).reversed()
.thenComparing(PingData::getAddress);

/**
* Detects a network partition and decides if the node belongs to the winning partition.
* <p>
Expand All @@ -74,12 +252,11 @@ public void setJpaConnectionProviderFactory(JpaConnectionProviderFactory factory
*/
public HealthStatus healthStatus() {
try {
// maybe create an index, and a query to return coordinators only?
return readFromDB(cluster_name)
.stream()
.filter(PingData::isCoord)
.sorted(SPLIT_BRAIN_DECIDER)
.map(PingData::getAddress)
.sorted()
.findFirst()
.map(view.getCoord()::equals)
.map(isCoordinatorInView -> isCoordinatorInView ? HealthStatus.HEALTHY : HealthStatus.UNHEALTHY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

import org.keycloak.Config;
import org.keycloak.common.util.Retry;
import org.keycloak.common.util.Time;
import org.keycloak.config.CachingOptions;
import org.keycloak.config.Option;
import org.keycloak.connections.infinispan.InfinispanConnectionSpi;
Expand Down Expand Up @@ -307,12 +308,13 @@ private static long getNextSequence(KeycloakSessionFactory sf, long highestSeque
private static Address insertSequenceInTable(JpaConnectionProvider cp, String clusterName, String tableName, long mySequence) {
ExtendedUUID address = new ExtendedUUID(0, mySequence);
cp.getEntityManager().<Connection>runWithConnection(con -> {
try (PreparedStatement s = con.prepareStatement("INSERT INTO %s values (?, ?, ?, ?, ?)".formatted(tableName))) {
try (PreparedStatement s = con.prepareStatement("INSERT INTO %s (address, name, cluster_name, ip, coord, last_update) values (?, ?, ?, ?, ?, ?)".formatted(tableName))) {
s.setString(1, org.jgroups.util.Util.addressToString(new UUID(address.getMostSignificantBits(), address.getLeastSignificantBits()))); // address
s.setString(2, "(starting)"); // name
s.setString(3, clusterName); // cluster name
s.setString(4, "127.0.0.1:0"); // ip = new IpAddress("localhost", 0).toString()
s.setBoolean(5, false); // coord
s.setLong(6, Time.currentTime()); // last_update
s.execute();
}
});
Expand All @@ -329,8 +331,8 @@ private static List<ProtocolConfiguration> getProtocolConfigurations(String tabl
// "cluster" cannot be used with Oracle DB as it's a reserved word.
"clear_sql", String.format("DELETE from %s WHERE cluster_name=?", tableName),
"delete_single_sql", String.format("DELETE from %s WHERE address=?", tableName),
"insert_single_sql", String.format("INSERT INTO %s values (?, ?, ?, ?, ?)", tableName),
"select_all_pingdata_sql", String.format("SELECT address, name, ip, coord FROM %s WHERE cluster_name=?", tableName),
"insert_single_sql", String.format("INSERT INTO %s (address, name, cluster_name, ip, coord, last_update, coordinated_by) values (?, ?, ?, ?, ?, ?, ?)", tableName),
"select_all_pingdata_sql", String.format("SELECT address, name, ip, coord, coordinated_by, last_update FROM %s WHERE cluster_name=?", tableName),
// This guarantees cleanup of stale data
"remove_all_data_on_view_change", "true",
// This guarantees that merging happens even after the info writer completed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@

package org.keycloak.jgroups.protocol;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jgroups.Address;
import org.jgroups.View;
import org.jgroups.protocols.PingData;
import org.jgroups.util.UUID;

/**
* A controllable KEYCLOAK_JDBC_PING2 where we can overwrite the view, the data returned from the database, and simulate exceptions.
Expand All @@ -40,8 +43,27 @@ protected List<PingData> readFromDB(String cluster) throws Exception {
}

public void setPingData(List<Address> coordinators) {
setPingData(coordinators, Map.of());
}

public void setPingData(List<Address> coordinators, Map<Address, Integer> addressCount) {
this.pingData = coordinators.stream()
.map(address -> new PingData(address, true).coord(true))
.flatMap(address -> {
ArrayList<PingData> partition = new ArrayList<>();
PingData coord = new PingData(address, true).coord(true);
partition.add(coord);
ArrayList<Address> members = new ArrayList<>();
members.add(address);
if (addressCount.containsKey(address)) {
for (int i = 0; i < addressCount.get(address); i++) {
UUID a = new UUID(UUID.randomUUID());
partition.add(new PingData(a, true));
members.add(a);
}
}
coord.mbrs(members);
return partition.stream();
})
.toList();
}

Expand Down
Loading
Loading
0