Skip to content

Instantly share code, notes, and snippets.

@kay
Last active December 17, 2015 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kay/5652895 to your computer and use it in GitHub Desktop.
Save kay/5652895 to your computer and use it in GitHub Desktop.
public class FailoverManager implements AutoCloseable, ChannelListener, Receiver {
private static final Logger LOGGER = LoggerFactory.getLogger(FailoverManager.class);
private static final String HA_CLUSTER = "ha-cluster";
private final JChannel channel;
private final int maximumClusterSize;
private final LeadershipResolver decider;
public FailoverManager(final String configName,
final String applicationGroup,
final int maximumClusterSize,
final LeadershipListener leadershipListener)
throws HighAvailabilityException {
if (maximumClusterSize < 3) {
throw new IllegalArgumentException("Cluster must contain at least 3 members");
}
this.maximumClusterSize = maximumClusterSize;
try {
this.channel = new JChannel(configName);
this.channel.addChannelListener(this);
this.channel.setReceiver(this);
this.decider = new LeadershipResolver(this.channel, applicationGroup, leadershipListener);
this.channel.connect(HA_CLUSTER);
} catch (final Exception e) {
throw new HighAvailabilityException("Failed to initialise channel '" + applicationGroup
+ "' and connect to '" + HA_CLUSTER + "'", e);
}
}
private boolean isMajority(final int currentClusterSize) {
final int majorityThreshold = (this.maximumClusterSize / 2) + 1;
return (currentClusterSize >= majorityThreshold);
}
@Override
public void viewAccepted(final View newView) {
LOGGER.info("View accepted {}", newView);
if (isMajority(newView.getMembers().size())) {
this.decider.tryLeadership();
} else {
this.decider.surrenderLeadership();
}
}
@Override
public void close() {
this.channel.close();
this.decider.close();
}
/* Other methods omitted for brevity */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment