Switches this node to leader role. Sets local endpoint as current leader.
Clears (pre)candidate states. Initializes leader state for current members.
501166
public void toLeader() {
        role = RaftRole.LEADER;
        leader(localEndpoint);
        preCandidateState = null;
        candidateState = null;
        leaderState = new LeaderState(lastGroupMembers.remoteMembers(), log.lastLogOrSnapshotIndex());
    }
235404
public void resetCoordinator() {

        final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();

        if (isTracingEnabled && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "Resetting uow coordinator to null");
        }

        uowCoord = null;

    }
390138
private void becomeFollowerWithoutUpdatingCurrentTerm(long currentTerm, @Nullable String newLeader) {
        logRoleChange(currentTerm, role, Role.FOLLOWER);

        stopHeartbeatTimeout();

        setFollowerState(newLeader);
    }
796213
ServerContext setLeader(int leader) {
    if (this.leader != leader) {
      // 0 indicates no leader.
      if (leader == 0) {
        this.leader = 0;
      } else {
        // If a valid leader ID was specified, it must be a member that's currently a member of the
        // ACTIVE members configuration. Note that we don't throw exceptions for unknown members. It's
        // possible that a failure following a configuration change could result in an unknown leader
        // sending AppendRequest to this server. Simply configure the leader if it's known.
        ServerMember member = cluster.member(leader);
        if (member != null) {
          this.leader = leader;
          LOGGER.info("{} - Found leader {}", cluster.member().address(), member.address());
          electionListeners.forEach(l -> l.accept(member));
          cluster.identify();
        }
      }

      this.lastVotedFor = 0;
      meta.storeVote(0);
    }
    return this;
  }
1345578
public void run() {
    LOG.info("The server runs and prepares for leader election");
    if (failoverWatcher.blockUntilActive()) {
      LOG.info("The server becomes active master and prepare to do business logic");
      doAsActiveServer();
    }
    failoverWatcher.close();
    LOG.info("The server exits after running business logic");
  }
1232651
public void start() throws Exception {
		try {
			leaderElectionService.start(this);
		} catch (Exception e) {
			log.error("Could not start the JobManager because the leader election service did not start.", e);
			throw new Exception("Could not start the leader election service.", e);
		}
	}
378211
def up(self, role, root_priority, root_times):
        
        self.port_priority = root_priority
        self.port_times = root_times

        state = (PORT_STATE_LISTEN if self.config_enable
                 else PORT_STATE_DISABLE)
        self._change_role(role)
        self._change_status(state)
1114043
def rebalance_leaders(self):
        
        opt_leader_cnt = len(self.cluster_topology.partitions) // len(self.cluster_topology.brokers)
        # Balanced brokers transfer leadership to their under-balanced followers
        self.rebalancing_non_followers(opt_leader_cnt)
321738
function (oNode) {

				// do not count the artifical root node
				if (!oNode || !oNode.isArtificial) {
					iNodeCounter++;
				}

				if (oNode) {
					// Always reset selectAllMode
					oNode.nodeState.selectAllMode = false;

					if (this._mTreeState.selected[oNode.groupID]) {
						// remember changed index, push it to the limit!
						if (!oNode.isArtificial) {
							aChangedIndices.push(iNodeCounter);
						}
						// deslect the node
						this.setNodeSelection(oNode.nodeState, false);

						//also remember the old lead index
						if (oNode.groupID === this._sLeadSelectionGroupID) {
							iOldLeadIndex = iNodeCounter;
						}

						return true;
					}
				}
			}
60116
private void confirmLeader(final EmbeddedLeaderElectionService service, final UUID leaderSessionId) {
		synchronized (lock) {
			// if the service was shut down in the meantime, ignore this confirmation
			if (!service.running || shutdown) {
				return;
			}

			try {
				// check if the confirmation is for the same grant, or whether it is a stale grant
				if (service == currentLeaderProposed && currentLeaderSessionId.equals(leaderSessionId)) {
					final String address = service.contender.getAddress();
					LOG.info("Received confirmation of leadership for leader {} , session={}", address, leaderSessionId);

					// mark leadership
					currentLeaderConfirmed = service;
					currentLeaderAddress = address;
					currentLeaderProposed = null;

					// notify all listeners
					notifyAllListeners(address, leaderSessionId);
				}
				else {
					LOG.debug("Received confirmation of leadership for a stale leadership grant. Ignoring.");
				}
			}
			catch (Throwable t) {
				fatalError(t);
			}
		}
	}
859129
def refresh_leader_status(self, instance):
        
        if not self.leader_candidate:
            return

        leader_status = self.kubeutil.is_leader
        self.kubeutil.refresh_leader()

        # nothing changed, no-op
        if leader_status == self.kubeutil.is_leader:
            return
        # else, reset the event collection config
        else:
            self.log.info("Leader status changed, updating event collection config...")
            self._configure_event_collection(instance)
929155
public void start() throws Exception
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");

        if ( leaderLatch != null && ownsLeaderLatch)
        {
            leaderLatch.start();
        }
    }
570457
protected boolean updateTermAndLeader(long term, int leader) {
    // If the request indicates a term that is greater than the current term or no leader has been
    // set for the current term, update leader and term.
    if (term > context.getTerm() || (term == context.getTerm() && context.getLeader() == null && leader != 0)) {
      context.setTerm(term);
      context.setLeader(leader);

      // Reset the current cluster configuration to the last committed configuration when a leader change occurs.
      context.getClusterState().reset();
      return true;
    }
    return false;
  }
270850
protected function initializeRoles()
    {
        if ($this->roles !== null) {
            return;
        }
        $this->roles = [];
        foreach ($this->roleIdentifiers as $key => $roleIdentifier) {
            // check for and clean up roles no longer available
            if ($this->policyService->hasRole($roleIdentifier)) {
                $this->roles[$roleIdentifier] = $this->policyService->getRole($roleIdentifier);
            } else {
                unset($this->roleIdentifiers[$key]);
            }
        }
    }
974662
@Override
	public void start(LeaderContender contender) throws Exception {
		checkNotNull(contender, "contender");

		synchronized (lock) {
			checkState(!shutdown, "service is shut down");
			checkState(proposedLeader == null, "service already started");

			// directly grant leadership to the given contender
			proposedLeader = contender;
			notificationExecutor.execute(new GrantLeadershipCall(contender, leaderId));
		}
	}
350460
private CompletableFuture<Void> commitInitialEntries() {
    // The Raft protocol dictates that leaders cannot commit entries from previous terms until
    // at least one entry from their current term has been stored on a majority of servers. Thus,
    // we force entries to be appended up to the leader's no-op entry. The LeaderAppender will ensure
    // that the commitIndex is not increased until the no-op entry (appender.index()) is committed.
    CompletableFuture<Void> future = new CompletableFuture<>();
    appender.appendEntries(appender.index()).whenComplete((resultIndex, error) -> {
      context.checkThread();
      if (isOpen()) {
        if (error == null) {
          context.getStateMachine().apply(resultIndex);
          future.complete(null);
        } else {
          context.setLeader(0);
          context.transition(CopycatServer.State.FOLLOWER);
        }
      }
    });
    return future;
  }
572436
function LeaderElection(client, path, id) {
  EventEmitter.call(this);

  /**
   * Ref. to client.
   *
   * @type {Rorschach}
   */
  this.client = client;


  /**
   * ZooKeeper path where participants' nodes exist.
   *
   * @type {String}
   */
  this.path = path;


  /**
   * Id of participant. It's kept in node.
   *
   * @type {String}
   */
  this.id = id;


  /**
   * Leadership state
   *
   * @type {Boolean}
   */
  this.isLeader = false;


  /**
   * Initial state.
   *
   * @type {State}
   */
  this.state = State.LATENT;
}