use of io.kubernetes.client.extended.leaderelection.LeaderElectionConfig in project java by kubernetes-client.
the class LeaderElectorTest method makeAndRunLeaderElectorAsync.
private LeaderElector makeAndRunLeaderElectorAsync(String candidateId, CyclicBarrier startBarrier, Runnable startBeingLeader, Runnable stopBeingLeader, ApiClient apiClient) {
Lock lock = makeLock(candidateId, NAMESPACE, LOCK_RESOURCE_NAME, apiClient);
LeaderElectionConfig leaderElectionConfig = new LeaderElectionConfig(lock, Duration.ofSeconds(30), Duration.ofSeconds(23), Duration.ofSeconds(3));
LeaderElector leaderElector = new LeaderElector(leaderElectionConfig);
Thread thread = new Thread(() -> {
if (startBarrier != null) {
try {
startBarrier.await();
} catch (InterruptedException | BrokenBarrierException ex) {
LOGGER.error("startBarrier.await() failed", ex);
return;
}
}
leaderElector.run(startBeingLeader, stopBeingLeader);
}, String.format("%s-leader-elector-main", candidateId));
thread.setDaemon(true);
thread.start();
return leaderElector;
}
use of io.kubernetes.client.extended.leaderelection.LeaderElectionConfig in project java by kubernetes-client.
the class LeaderElectingControllerTest method testLeaderElectingController.
@Test(timeout = 90000)
public void testLeaderElectingController() throws ApiException, InterruptedException {
AtomicReference<LeaderElectionRecord> record = new AtomicReference<>();
record.set(new LeaderElectionRecord());
Semaphore latch = new Semaphore(2);
Semaphore controllerLatch = new Semaphore(2);
when(mockLock.identity()).thenReturn("foo");
when(mockLock.get()).thenThrow(new ApiException("Record Not Found", HttpURLConnection.HTTP_NOT_FOUND, null, null)).thenReturn(record.get());
doAnswer(invocationOnMock -> {
record.set(invocationOnMock.getArgument(0));
latch.release();
return true;
}).when(mockLock).create(any());
doAnswer(invocationOnMock -> {
latch.release();
return false;
}).when(mockLock).update(any());
doAnswer(invocationOnMock -> {
controllerLatch.release();
return null;
}).when(mockController).run();
doAnswer(invocationOnMock -> {
controllerLatch.release();
return null;
}).when(mockController).shutdown();
LeaderElectingController leaderElectingController = new LeaderElectingController(new LeaderElector(new LeaderElectionConfig(mockLock, Duration.ofMillis(300), Duration.ofMillis(200), Duration.ofMillis(100))), mockController);
latch.acquire(2);
controllerLatch.acquire(2);
Thread controllerThread = new Thread(leaderElectingController::run);
controllerThread.start();
latch.acquire(2);
controllerThread.interrupt();
verify(mockLock, times(1)).create(any());
verify(mockLock, atLeastOnce()).update(any());
controllerLatch.acquire(2);
verify(mockController, times(1)).run();
verify(mockController, times(1)).shutdown();
}
use of io.kubernetes.client.extended.leaderelection.LeaderElectionConfig in project java by kubernetes-client.
the class LeaderElectionExample method main.
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
// New
String appNamespace = "default";
String appName = "leader-election-foobar";
// Anything unique
String lockHolderIdentityName = UUID.randomUUID().toString();
EndpointsLock lock = new EndpointsLock(appNamespace, appName, lockHolderIdentityName);
LeaderElectionConfig leaderElectionConfig = new LeaderElectionConfig(lock, Duration.ofMillis(10000), Duration.ofMillis(8000), Duration.ofMillis(2000));
try (LeaderElector leaderElector = new LeaderElector(leaderElectionConfig)) {
leaderElector.run(() -> {
System.out.println("Do something when getting leadership.");
}, () -> {
System.out.println("Do something when losing leadership.");
});
}
}
use of io.kubernetes.client.extended.leaderelection.LeaderElectionConfig in project java by kubernetes-client.
the class ControllerExample method main.
public static void main(String[] args) throws IOException {
CoreV1Api coreV1Api = new CoreV1Api();
ApiClient apiClient = coreV1Api.getApiClient();
OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
apiClient.setHttpClient(httpClient);
// instantiating an informer-factory, and there should be only one informer-factory
// globally.
SharedInformerFactory informerFactory = new SharedInformerFactory();
// registering node-informer into the informer-factory.
SharedIndexInformer<V1Node> nodeInformer = informerFactory.sharedIndexInformerFor((CallGeneratorParams params) -> {
return coreV1Api.listNodeCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
}, V1Node.class, V1NodeList.class);
informerFactory.startAllRegisteredInformers();
EventBroadcaster eventBroadcaster = new LegacyEventBroadcaster(coreV1Api);
// nodeReconciler prints node information on events
NodePrintingReconciler nodeReconciler = new NodePrintingReconciler(nodeInformer, eventBroadcaster.newRecorder(new V1EventSource().host("localhost").component("node-printer")));
// Use builder library to construct a default controller.
Controller controller = ControllerBuilder.defaultBuilder(informerFactory).watch((workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Node.class, workQueue).withWorkQueueKeyFunc((V1Node node) -> new Request(node.getMetadata().getName())).withOnAddFilter((V1Node createdNode) -> createdNode.getMetadata().getName().startsWith(// optional, set onAdd filter
"docker-")).withOnUpdateFilter((V1Node oldNode, V1Node newNode) -> newNode.getMetadata().getName().startsWith(// optional, set onUpdate filter
"docker-")).withOnDeleteFilter((V1Node deletedNode, Boolean stateUnknown) -> deletedNode.getMetadata().getName().startsWith(// optional, set onDelete filter
"docker-")).build()).withReconciler(// required, set the actual reconciler
nodeReconciler).withName(// optional, set name for controller
"node-printing-controller").withWorkerCount(// optional, set worker thread count
4).withReadyFunc(// optional, only starts controller when the
nodeInformer::hasSynced).build();
// Use builder library to manage one or multiple controllers.
ControllerManager controllerManager = ControllerBuilder.controllerManagerBuilder(informerFactory).addController(controller).build();
LeaderElectingController leaderElectingController = new LeaderElectingController(new LeaderElector(new LeaderElectionConfig(new EndpointsLock("kube-system", "leader-election", "foo"), Duration.ofMillis(10000), Duration.ofMillis(8000), Duration.ofMillis(5000))), controllerManager);
leaderElectingController.run();
}
use of io.kubernetes.client.extended.leaderelection.LeaderElectionConfig in project druid by druid-io.
the class DefaultK8sLeaderElectorFactory method create.
@Override
public K8sLeaderElector create(String candidateId, String namespace, String lockResourceName) {
Lock lock = createLock(candidateId, namespace, lockResourceName, realK8sClient);
LeaderElectionConfig leaderElectionConfig = new LeaderElectionConfig(lock, Duration.ofMillis(discoveryConfig.getLeaseDuration().getMillis()), Duration.ofMillis(discoveryConfig.getRenewDeadline().getMillis()), Duration.ofMillis(discoveryConfig.getRetryPeriod().getMillis()));
LeaderElector leaderElector = new LeaderElector(leaderElectionConfig);
return new K8sLeaderElector() {
@Override
public String getCurrentLeader() {
try {
return lock.get().getHolderIdentity();
} catch (ApiException ex) {
throw new RE(ex, "Failed to get current leader for [%s]", lockResourceName);
}
}
@Override
public void run(Runnable startLeadingHook, Runnable stopLeadingHook) {
leaderElector.run(startLeadingHook, stopLeadingHook);
}
};
}
Aggregations