@Test public void test() throws Exception { Timing timing = new Timing(); LeaderSelector leaderSelector = null; CuratorFramework client = CuratorFrameworkFactory.builder() .retryPolicy(new ExponentialBackoffRetry(100, 3)) .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .build(); try { client.start(); MyLeaderSelectorListener listener = new MyLeaderSelectorListener(); ExecutorService executorPool = Executors.newFixedThreadPool(20); leaderSelector = new LeaderSelector(client, "/test", threadFactory, executorPool, listener); leaderSelector.autoRequeue(); leaderSelector.start(); timing.sleepABit(); Assert.assertEquals(listener.getLeaderCount(), 1); } finally { CloseableUtils.closeQuietly(leaderSelector); CloseableUtils.closeQuietly(client); } }
@VisibleForTesting void reset() throws Exception { setLeadership(false); setNode(null); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if (debugResetWaitLatch != null) { debugResetWaitLatch.await(); debugResetWaitLatch = null; } if (event.getResultCode() == KeeperException.Code.OK.intValue()) { setNode(event.getName()); getChildren(); } else { log.error("getChildren() failed. rc = " + event.getResultCode()); } } }; client .create() .creatingParentsIfNeeded() .withProtection() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .inBackground(callback) .forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id)); }
private void internalStart() throws Exception { hasLeadership.set(false); if (ourPath != null) { client.delete().guaranteed().inBackground().forPath(ourPath); } ourPath = client .create() .withProtection() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id)); checkForLeadership(); }
/** * Return the id for the current leader. If for some reason there is no current leader, a dummy * participant is returned. * * <p><B>NOTE</B> - this method polls the ZK server. Therefore it can possibly return a value that * does not match {@link #hasLeadership()} as hasLeadership uses a local field of the class. * * @return leader * @throws Exception ZK errors, interruptions, etc. */ public Participant getLeader() throws Exception { Collection<String> participantNodes = LockInternals.getParticipantNodes(client, latchPath, LOCK_NAME, sorter); return LeaderSelector.getLeader(client, participantNodes); }