/*** Check if the candidate with the given n_* sequence number is the leader.* If it is, set the leaderId on the leader zk node. If it is not, start* watching the candidate that is in line before this one - if it goes down, check* if this candidate is the leader again.** @param replacement has someone else been the leader already?*/private void checkIfIamLeader(final ElectionContext context, boolean replacement) throws KeeperException,InterruptedException, IOException {context.checkIfIamLeaderFired();// get all other numbers...final String holdElectionPath = context.electionPath + ELECTION_NODE;List<String> seqs = zkClient.getChildren(holdElectionPath, null, true);sortSeqs(seqs);String leaderSeqNodeName = context.leaderSeqPath.substring(context.leaderSeqPath.lastIndexOf('/') + 1);if (!seqs.contains(leaderSeqNodeName)) {log.warn("Our node is no longer in line to be leader");return;}// If any double-registrations exist for me, remove all but this latest one!// TODO: can we even get into this state?String prefix = zkClient.getSolrZooKeeper().getSessionId() + "-" + context.id + "-";Iterator<String> it = seqs.iterator();while (it.hasNext()) {String elec = it.next();if (!elec.equals(leaderSeqNodeName) && elec.startsWith(prefix)) {try {String toDelete = holdElectionPath + "/" + elec;log.warn("Deleting duplicate registration: {}", toDelete);zkClient.delete(toDelete, -1, true);} catch (KeeperException.NoNodeException e) {// ignore}it.remove();}}if (leaderSeqNodeName.equals(seqs.get(0))) {// I am the leadertry {runIamLeaderProcess(context, replacement);} catch (KeeperException.NodeExistsException e) {log.error("node exists",e);retryElection(context, false);return;}} else {// I am not the leader - watch the node below meString toWatch = seqs.get(0);for (String node : seqs) {if (leaderSeqNodeName.equals(node)) {break;}toWatch = node;}try {String watchedNode = holdElectionPath + "/" + toWatch;zkClient.getData(watchedNode, watcher = new ElectionWatcher(context.leaderSeqPath, watchedNode, getSeq(context.leaderSeqPath), context), null, true);log.debug("Watching path {} to know if I could be the leader", watchedNode);} catch (KeeperException.SessionExpiredException e) {throw e;} catch (KeeperException.NoNodeException e) {// the previous node disappeared, check if we are the leader againcheckIfIamLeader(context, true);} catch (KeeperException e) {// we couldn't set our watch for some other reason, retrylog.warn("Failed setting watch", e);checkIfIamLeader(context, true);}}}