Triggers a preferred leader elections for the provided list of partitions. If no list of
 partitions is provided, the preferred leader will be elected for all partitions in the cluster.
506794
def preferred_leader_election(partitions: nil)
      partitions = self.partitions if partitions.nil?
      result = zk.create(path: "/admin/preferred_replica_election", data: JSON.generate(version: 1, partitions: partitions))
      case result.fetch(:rc)
      when Zookeeper::Constants::ZOK
        return true
      when Zookeeper::Constants::ZNODEEXISTS
        raise Kazoo::Error, "Another preferred leader election is still in progress"
      else
        raise Kazoo::Error, "Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}"
      end
    end
85809
private synchronized CompletableFuture<Void> join() {
    joinFuture = new CompletableFuture<>();

    context.getThreadContext().executor().execute(() -> {
      // Transition the server to the appropriate state for the local member type.
      context.transition(member.type());

      // Attempt to join the cluster. If the local member is ACTIVE then failing to join the cluster
      // will result in the member attempting to get elected. This allows initial clusters to form.
      List<MemberState> activeMembers = getActiveMemberStates();
      if (!activeMembers.isEmpty()) {
        join(getActiveMemberStates().iterator());
      } else {
        joinFuture.complete(null);
      }
    });

    return joinFuture.whenComplete((result, error) -> joinFuture = null);
  }
898105
private void configure(Member.Type type, CompletableFuture<Void> future) {
    // Set a timer to retry the attempt to leave the cluster.
    configureTimeout = cluster.getContext().getThreadContext().schedule(cluster.getContext().getElectionTimeout(), () -> {
      configure(type, future);
    });

    // Attempt to leave the cluster by submitting a LeaveRequest directly to the server state.
    // Non-leader states should forward the request to the leader if there is one. Leader states
    // will log, replicate, and commit the reconfiguration.
    cluster.getContext().getServerState().reconfigure(ReconfigureRequest.builder()
      .withIndex(cluster.getConfiguration().index())
      .withTerm(cluster.getConfiguration().term())
      .withMember(new ServerMember(type, serverAddress(), clientAddress(), updated))
      .build()).whenComplete((response, error) -> {
      if (error == null) {
        if (response.status() == Response.Status.OK) {
          cancelConfigureTimer();
          cluster.configure(new Configuration(response.index(), response.term(), response.timestamp(), response.members()));
          future.complete(null);
        } else if (response.error() == null || response.error() == CopycatError.Type.NO_LEADER_ERROR) {
          cancelConfigureTimer();
          configureTimeout = cluster.getContext().getThreadContext().schedule(cluster.getContext().getElectionTimeout().multipliedBy(2), () -> configure(type, future));
        } else {
          cancelConfigureTimer();
          future.completeExceptionally(response.error().createException());
        }
      }
    });
  }
848838
public static boolean checkPartitionBelongsToNode(int partition,
                                                      int nodeId,
                                                      Cluster cluster,
                                                      StoreDefinition storeDef) {
        List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();
        List<Integer> replicatingPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,
                                                                                                 cluster)
                                                                          .getReplicatingPartitionList(partition);
        replicatingPartitions.retainAll(nodePartitions);
        return replicatingPartitions.size() > 0;
    }
1233761
public void setBackupSelectionsList(java.util.Collection<BackupSelectionsListMember> backupSelectionsList) {
        if (backupSelectionsList == null) {
            this.backupSelectionsList = null;
            return;
        }

        this.backupSelectionsList = new java.util.ArrayList<BackupSelectionsListMember>(backupSelectionsList);
    }
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;
  }
654424
@Override
  public void join(String peer) throws Exception {
    LOG.debug("Follower joins in.");
    try {
      LOG.debug("Query leader from {}", peer);
      Message query = MessageBuilder.buildQueryLeader();
      MessageTuple tuple = null;
      while (true) {
        // The joiner might gets started before the cluster gets started.
        // Instead of reporting failure immediately, the follower will retry
        // joining the cluster until joining the cluster successfully.
        try {
          sendMessage(peer, query);
          tuple = filter.getExpectedMessage(MessageType.QUERY_LEADER_REPLY,
                                            peer, config.getTimeoutMs());
          break;
        } catch (TimeoutException ex) {
          long retryInterval = 1;
          LOG.warn("Timeout while contacting leader, going to retry after {} "
              + "second.", retryInterval);
          // Waits for 1 second.
          Thread.sleep(retryInterval * 1000);
        }
      }
      this.electedLeader = tuple.getMessage().getReply().getLeader();
      LOG.debug("Got current leader {}", this.electedLeader);

      /* -- Synchronizing phase -- */
      while (true) {
        try {
          joinSynchronization();
          break;
        } catch (TimeoutException | BackToElectionException ex) {
          LOG.debug("Timeout({} ms) in synchronizing, retrying. Last zxid : {}",
                    getSyncTimeoutMs(),
                    persistence.getLatestZxid());
          transport.clear(electedLeader);
          clearMessageQueue();
        }
      }
      // See if it can be restored from the snapshot file.
      restoreFromSnapshot();
      // Delivers all transactions in log before entering broadcasting phase.
      deliverUndeliveredTxns();

      /* -- Broadcasting phase -- */
      // Initialize the vote for leader election.
      this.election.specifyLeader(this.electedLeader);
      changePhase(Phase.BROADCASTING);
      accepting();
    } catch (InterruptedException e) {
      LOG.debug("Participant is canceled by user.");
      throw e;
    } catch (TimeoutException e) {
      LOG.debug("Didn't hear message from {} for {} milliseconds. Going"
                + " back to leader election.",
                this.electedLeader,
                this.config.getTimeoutMs());
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (BackToElectionException e) {
      LOG.debug("Got GO_BACK message from queue, going back to electing.");
      if (persistence.getLastSeenConfig() == null) {
        throw new JoinFailure("Fails to join cluster.");
      }
    } catch (LeftCluster e) {
      LOG.debug("Exit running : {}", e.getMessage());
      throw e;
    } catch (Exception e) {
      LOG.error("Caught exception", e);
      throw e;
    } finally {
      changePhase(Phase.FINALIZING);
    }
  }
1071155
public boolean addMember(Principal principal)
   {
       if(groupMembers.contains(principal))
           return false;

       groupMembers.add(principal);
       return true;
   }
175105
public static Assignments cluster(Matrix matrix,
                                      int numClusters,
                                      int numRepetitions,
                                      CriterionFunction criterion) {
        return cluster(matrix, numClusters, numRepetitions,
                       new RandomSeed(), criterion);
    }
566022
private int pollRemovedCountHolders(AtomicReferenceArray<Queue<Integer>> removedCountHolders) {
        int count = 0;
        for (int i = 0; i < partitionCount; i++) {
            Queue<Integer> removalCounts = removedCountHolders.get(i);
            count += removalCounts.poll();
        }
        return count;
    }
482901
public MemberSelector reset() {
    if (selectionsIterator != null) {
      this.selections = strategy.selectConnections(leader, Lists.newLinkedList(members));
      this.selectionsIterator = null;
    }
    return this;
  }
871643
private boolean registerAndConfirmIfImIt() throws ClusterInfoException {
        // reset the subdir watcher
        final Collection<String> imItSubdirs = utils.persistentGetSubdir(utils.leaderDir, this);

        // "there can be only one"
        if (imItSubdirs.size() > 1)
            throw new ClusterInfoException(
                    "This is IMPOSSIBLE. There's more than one subdir of " + utils.leaderDir + ". They include " + imItSubdirs);

        // make sure it's still mine.
        @SuppressWarnings("unchecked")
        final C registered = (C) session.getData(utils.masterDetermineDir, null);

        return utils.thisNodeAddress.equals(registered); // am I it, or not?
    }
810570
private void triggerMasterToAssignPartitions() {
        if (!shouldTriggerMasterToAssignPartitions()) {
            return;
        }

        ClusterServiceImpl clusterService = node.getClusterService();

        ClusterState clusterState = clusterService.getClusterState();
        if (!clusterState.isMigrationAllowed()) {
            logger.warning("Partitions can't be assigned since cluster-state=" + clusterState);
            return;
        }

        final Address masterAddress = clusterService.getMasterAddress();
        if (masterAddress == null || masterAddress.equals(node.getThisAddress())) {
            return;
        }

        if (masterTriggered.compareAndSet(false, true)) {
            InternalOperationService operationService = nodeEngine.getOperationService();
            ICompletableFuture<PartitionRuntimeState> future =
                    operationService.invokeOnTarget(SERVICE_NAME, new AssignPartitions(), masterAddress);
            future.andThen(new ExecutionCallback<PartitionRuntimeState>() {
                @Override
                public void onResponse(PartitionRuntimeState partitionState) {
                    resetMasterTriggeredFlag();
                    if (partitionState != null) {
                        partitionState.setMaster(masterAddress);
                        processPartitionRuntimeState(partitionState);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    resetMasterTriggeredFlag();
                    logger.severe(t);
                }
            });

            masterTrigger.executeWithDelay();
        }
    }
1363656
def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, force, scheduled=None):
    

    dcs = get_dcs(obj, cluster_name)
    cluster = dcs.get_cluster()

    if action == 'switchover' and cluster.leader is None:
        raise PatroniCtlException('This cluster has no master')

    if master is None:
        if force or action == 'failover':
            master = cluster.leader and cluster.leader.name
        else:
            master = click.prompt('Master', type=str, default=cluster.leader.member.name)

    if master is not None and cluster.leader and cluster.leader.member.name != master:
        raise PatroniCtlException('Member {0} is not the leader of cluster {1}'.format(master, cluster_name))

    # excluding members with nofailover tag
    candidate_names = [str(m.name) for m in cluster.members if m.name != master and not m.nofailover]
    # We sort the names for consistent output to the client
    candidate_names.sort()

    if not candidate_names:
        raise PatroniCtlException('No candidates found to {0} to'.format(action))

    if candidate is None and not force:
        candidate = click.prompt('Candidate ' + str(candidate_names), type=str, default='')

    if action == 'failover' and not candidate:
        raise PatroniCtlException('Failover could be performed only to a specific candidate')

    if candidate == master:
        raise PatroniCtlException(action.title() + ' target and source are the same.')

    if candidate and candidate not in candidate_names:
        raise PatroniCtlException('Member {0} does not exist in cluster {1}'.format(candidate, cluster_name))

    scheduled_at_str = None
    scheduled_at = None

    if action == 'switchover':
        if scheduled is None and not force:
            scheduled = click.prompt('When should the switchover take place (e.g. 2015-10-01T14:30) ',
                                     type=str, default='now')

        scheduled_at = parse_scheduled(scheduled)
        if scheduled_at:
            if cluster.is_paused():
                raise PatroniCtlException("Can't schedule switchover in the paused state")
            scheduled_at_str = scheduled_at.isoformat()

    failover_value = {'leader': master, 'candidate': candidate, 'scheduled_at': scheduled_at_str}

    logging.debug(failover_value)

    # By now we have established that the leader exists and the candidate exists
    click.echo('Current cluster topology')
    output_members(dcs.get_cluster(), cluster_name)

    if not force:
        demote_msg = ', demoting current master ' + master if master else ''

        if not click.confirm('Are you sure you want to {0} cluster {1}{2}?'.format(action, cluster_name, demote_msg)):
            raise PatroniCtlException('Aborting ' + action)

    r = None
    try:
        member = cluster.leader.member if cluster.leader else cluster.get_member(candidate, False)

        r = request_patroni(member, 'post', action, failover_value, auth_header(obj))

        # probably old patroni, which doesn't support switchover yet
        if r.status_code == 501 and action == 'switchover' and 'Server does not support this operation' in r.text:
            r = request_patroni(member, 'post', 'failover', failover_value, auth_header(obj))

        if r.status_code in (200, 202):
            logging.debug(r)
            cluster = dcs.get_cluster()
            logging.debug(cluster)
            click.echo('{0} {1}'.format(timestamp(), r.text))
        else:
            click.echo('{0} failed, details: {1}, {2}'.format(action.title(), r.status_code, r.text))
            return
    except Exception:
        logging.exception(r)
        logging.warning('Failing over to DCS')
        click.echo('{0} Could not {1} using Patroni api, falling back to DCS'.format(timestamp(), action))
        dcs.manual_failover(master, candidate, scheduled_at=scheduled_at)

    output_members(cluster, cluster_name)
898156
private void takeLeadership() {
    raft.setLeader(raft.getCluster().getMember().memberId());
    raft.getCluster().getRemoteMemberStates().forEach(m -> m.resetState(raft.getLog()));
  }
1102009
public Address elect(List<Address> list) {
		//Jgroups return addresses always in sorted order, jbcache does not change it.
		//For buddies its ok, since we get list from failing node :) 
		// in case shift is bigger than size
		int size = list.size();
		int index = (this.shift % size) +size;
		index = index % size;

		return list.get(index);

	}
321642
private String chooseFirstOccurence(String[] among_owners, String[] within_listgroup,
			String prior_tableName) {
		int index = CStringUtils.indexOf(within_listgroup, prior_tableName);
		for(int i = index-1; i >= 0; i-- ){
			String closest = within_listgroup[i];
			if(CStringUtils.indexOf(among_owners, closest) >= 0){
				return closest;
			}
		}
		return null;
	}