private void runElection()

in twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java [182:223]


  private void runElection() {
    LOG.debug("Running election for {}", zkNodePath);

    OperationFuture<NodeChildren> childrenFuture = zkClient.getChildren(zkFolderPath);
    Futures.addCallback(childrenFuture, new FutureCallback<NodeChildren>() {
      @Override
      public void onSuccess(NodeChildren result) {
        Optional<String> nodeToWatch = findNodeToWatch(result.getChildren());

        if (state == State.CANCELLED) {
          deleteNode();
          return;
        }

        if (nodeToWatch == null) {
          // zkNodePath unknown, need to run register.
          register();
          return;
        }

        if (nodeToWatch.isPresent()) {
          // Watch for deletion of largest node smaller than current node
          watchNode(zkFolderPath + "/" + nodeToWatch.get(), new LowerNodeWatcher());
        } else {
          // This is leader
          becomeLeader();
        }
      }

      @Override
      public void onFailure(Throwable t) {
        LOG.warn("Got exception during children fetch for {}. Retry.", zkFolderPath, t);
        // If cancel has been called before this callback and the zkNodePath is known, we can simply
        // delete the node. Otherwise, runElection() is needed to determine the zkNodePath if it is cancelled.
        if (state == State.CANCELLED && zkNodePath != null) {
          deleteNode();
        } else {
          runElection();
        }
      }
    }, executor);
  }