org.zodic.kubernetes.leader.LeaderRecordWatcher Maven / Gradle / Ivy
package org.zodic.kubernetes.leader;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LeaderRecordWatcher implements Watcher {
private static final Logger LOGGER = LoggerFactory.getLogger(LeaderRecordWatcher.class);
private final Object lock = new Object();
private final LeadershipController leadershipController;
private final LeaderInfo leaderInfo;
private final KubernetesClient kubernetesClient;
private Watch watch;
public LeaderRecordWatcher(LeaderInfo leaderInfo, LeadershipController leadershipController,
KubernetesClient kubernetesClient) {
this.leadershipController = leadershipController;
this.leaderInfo = leaderInfo;
this.kubernetesClient = kubernetesClient;
}
public void start() {
if (this.watch == null) {
synchronized (this.lock) {
if (this.watch == null) {
LOGGER.debug("Starting leader record watcher");
this.watch = this.kubernetesClient.configMaps()
.inNamespace(this.leaderInfo.getNamespace(this.kubernetesClient.getNamespace()))
.withName(this.leaderInfo.getConfigMapName()).watch(this);
}
}
}
}
public void stop() {
if (this.watch != null) {
synchronized (this.lock) {
if (this.watch != null) {
LOGGER.debug("Stopping leader record watcher");
this.watch.close();
this.watch = null;
}
}
}
}
@Override
public void eventReceived(Action action, ConfigMap configMap) {
LOGGER.debug("'{}' event received, triggering leadership update", action);
if (!Action.ERROR.equals(action)) {
this.leadershipController.update();
}
}
@Override
public void onClose(WatcherException cause) {
if (cause != null) {
synchronized (this.lock) {
LOGGER.warn("Watcher stopped unexpectedly, will restart", cause);
this.watch = null;
start();
}
}
}
}