Java Code Examples for org.elasticsearch.cluster.ClusterState#Builder

The following examples show how to use org.elasticsearch.cluster.ClusterState#Builder . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: anomaly-detection   File: HashRingTests.java    License: Apache License 2.0 6 votes vote down vote up
private void setNodeState(Map<String, String> attributesForNode1) {
    DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
    List<DiscoveryNode> discoveryNodes = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        DiscoveryNode node = null;
        if (i != 1) {
            node = createNode(Integer.toString(i), emptyMap());
        } else {
            node = createNode(Integer.toString(i), attributesForNode1);
        }

        discoBuilder = discoBuilder.add(node);
        discoveryNodes.add(node);
    }
    discoBuilder.localNodeId("1");
    discoBuilder.masterNodeId("0");
    ClusterState.Builder stateBuilder = ClusterState.builder(clusterService.getClusterName());
    stateBuilder.nodes(discoBuilder);
    ClusterState clusterState = stateBuilder.build();
    setState(clusterService.getClusterApplierService(), clusterState);
}
 
Example 2
Source Project: Elasticsearch   File: JoinClusterAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ClusterState execute(ClusterState currentState) {
    DiscoveryNodes.Builder nodesBuilder;
    nodesBuilder = DiscoveryNodes.builder(currentState.nodes());
    if (currentState.nodes().nodeExists(node.id())) {
        logger.debug("received a join request for an existing node [{}]", node);
        return currentState;
    } 
    // If this node is not in dead node list, then ignore this request
    ImmutableOpenMap<String, DiscoveryNode> deadNodes = clusterService.state().nodes().deadNodes();
    if (deadNodes.get(node.getIpPortAddress()) == null) {
        logger.warn("failed to find node [{}] in node list, ignore the join request", node);
        throw new IllegalStateException("could not find this node " + node + " from active node list and dead node list");
    }
    nodesBuilder.put(node);
    nodesBuilder.removeDeadNodeByIpPort(node);
    final ClusterState.Builder newStateBuilder = ClusterState.builder(currentState);
    newStateBuilder.nodes(nodesBuilder);
    ClusterState newState = newStateBuilder.build();
    return newState;
}
 
Example 3
Source Project: crate   File: PrimaryTermsTests.java    License: Apache License 2.0 6 votes vote down vote up
private void applyRerouteResult(ClusterState newClusterState) {
    ClusterState previousClusterState = this.clusterState;
    ClusterState.Builder builder = ClusterState.builder(newClusterState).incrementVersion();
    if (previousClusterState.routingTable() != newClusterState.routingTable()) {
        builder.routingTable(RoutingTable.builder(newClusterState.routingTable()).version(newClusterState.routingTable().version() + 1)
                                 .build());
    }
    if (previousClusterState.metaData() != newClusterState.metaData()) {
        builder.metaData(MetaData.builder(newClusterState.metaData()).version(newClusterState.metaData().version() + 1));
    }
    this.clusterState = builder.build();
    final ClusterStateHealth clusterHealth = new ClusterStateHealth(clusterState);
    logger.info("applied reroute. active shards: p [{}], t [{}], init shards: [{}], relocating: [{}]",
                clusterHealth.getActivePrimaryShards(), clusterHealth.getActiveShards(),
                clusterHealth.getInitializingShards(), clusterHealth.getRelocatingShards());
}
 
Example 4
Source Project: crate   File: ESIntegTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove any customs except for customs that we know all clients understand.
 *
 * @param clusterState the cluster state to remove possibly-unknown customs from
 * @return the cluster state with possibly-unknown customs removed
 */
private ClusterState removePluginCustoms(final ClusterState clusterState) {
    final ClusterState.Builder builder = ClusterState.builder(clusterState);
    clusterState.customs().keysIt().forEachRemaining(key -> {
        if (SAFE_CUSTOMS.contains(key) == false) {
            builder.removeCustom(key);
        }
    });
    final MetaData.Builder mdBuilder = MetaData.builder(clusterState.metaData());
    clusterState.metaData().customs().keysIt().forEachRemaining(key -> {
        if (SAFE_METADATA_CUSTOMS.contains(key) == false) {
            mdBuilder.removeCustom(key);
        }
    });
    builder.metaData(mdBuilder);
    return builder.build();
}
 
Example 5
public void testSucceedsEvenIfAllExclusionsAlreadyAdded() throws InterruptedException {
    final ClusterState state = clusterService.state();
    final ClusterState.Builder builder = builder(state);
    builder.metaData(MetaData.builder(state.metaData()).
            coordinationMetaData(
                    CoordinationMetaData.builder(state.coordinationMetaData())
                            .addVotingConfigExclusion(otherNode1Exclusion).
            build()));
    setState(clusterService, builder);

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    transportService.sendRequest(localNode, AddVotingConfigExclusionsAction.NAME,
        new AddVotingConfigExclusionsRequest(new String[]{"other1"}),
        expectSuccess(r -> {
            assertNotNull(r);
            countDownLatch.countDown();
        })
    );

    assertTrue(countDownLatch.await(30, TimeUnit.SECONDS));
    assertThat(clusterService.getClusterApplierService().state().getVotingConfigExclusions(),
            contains(otherNode1Exclusion));
}
 
Example 6
public void testSucceedsIfNodesAreRemovedWhileWaiting() throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final SetOnce<ClearVotingConfigExclusionsResponse> responseHolder = new SetOnce<>();

    transportService.sendRequest(localNode, ClearVotingConfigExclusionsAction.NAME,
        new ClearVotingConfigExclusionsRequest(),
        expectSuccess(r -> {
            responseHolder.set(r);
            countDownLatch.countDown();
        })
    );

    final ClusterState.Builder builder = builder(clusterService.state());
    builder.nodes(DiscoveryNodes.builder(clusterService.state().nodes()).remove(otherNode1).remove(otherNode2));
    setState(clusterService, builder);

    assertTrue(countDownLatch.await(30, TimeUnit.SECONDS));
    assertThat(clusterService.getClusterApplierService().state().getVotingConfigExclusions(), empty());
}
 
Example 7
Source Project: crate   File: JoinTaskExecutor.java    License: Apache License 2.0 5 votes vote down vote up
protected ClusterState.Builder becomeMasterAndTrimConflictingNodes(ClusterState currentState, List<Task> joiningNodes) {
    assert currentState.nodes().getMasterNodeId() == null : currentState;
    DiscoveryNodes currentNodes = currentState.nodes();
    DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(currentNodes);
    nodesBuilder.masterNodeId(currentState.nodes().getLocalNodeId());

    for (final Task joinTask : joiningNodes) {
        if (joinTask.isBecomeMasterTask() || joinTask.isFinishElectionTask()) {
            // noop
        } else {
            final DiscoveryNode joiningNode = joinTask.node();
            final DiscoveryNode nodeWithSameId = nodesBuilder.get(joiningNode.getId());
            if (nodeWithSameId != null && nodeWithSameId.equals(joiningNode) == false) {
                logger.debug("removing existing node [{}], which conflicts with incoming join from [{}]", nodeWithSameId, joiningNode);
                nodesBuilder.remove(nodeWithSameId.getId());
            }
            final DiscoveryNode nodeWithSameAddress = currentNodes.findByAddress(joiningNode.getAddress());
            if (nodeWithSameAddress != null && nodeWithSameAddress.equals(joiningNode) == false) {
                logger.debug("removing existing node [{}], which conflicts with incoming join from [{}]", nodeWithSameAddress,
                    joiningNode);
                nodesBuilder.remove(nodeWithSameAddress.getId());
            }
        }
    }


    // now trim any left over dead nodes - either left there when the previous master stepped down
    // or removed by us above
    ClusterState tmpState = ClusterState.builder(currentState).nodes(nodesBuilder).blocks(ClusterBlocks.builder()
        .blocks(currentState.blocks())
        .removeGlobalBlock(NoMasterBlockService.NO_MASTER_BLOCK_ID))
        .build();
    logger.trace("becomeMasterAndTrimConflictingNodes: {}", tmpState.nodes());
    allocationService.cleanCaches();
    return ClusterState.builder(allocationService.disassociateDeadNodes(tmpState, false, "removed dead nodes on election"));
}
 
Example 8
Source Project: crate   File: CoordinationStateTests.java    License: Apache License 2.0 5 votes vote down vote up
void setInitialState(VotingConfiguration initialConfig, long initialValue) {
    final ClusterState.Builder builder = ClusterState.builder(state.getLastAcceptedState());
    builder.metaData(MetaData.builder()
            .coordinationMetaData(CoordinationMetaData.builder()
                .lastAcceptedConfiguration(initialConfig)
                .lastCommittedConfiguration(initialConfig)
            .build()));
    state.setInitialState(setValue(builder.build(), initialValue));
}
 
Example 9
public void testResolveAndCheckMaximum() {
    final DiscoveryNode localNode
        = new DiscoveryNode("local", "local", buildNewFakeTransportAddress(), emptyMap(), singleton(Role.MASTER), Version.CURRENT);
    final VotingConfigExclusion localNodeExclusion = new VotingConfigExclusion(localNode);
    final DiscoveryNode otherNode1
        = new DiscoveryNode("other1", "other1", buildNewFakeTransportAddress(), emptyMap(), singleton(Role.MASTER), Version.CURRENT);
    final VotingConfigExclusion otherNode1Exclusion = new VotingConfigExclusion(otherNode1);
    final DiscoveryNode otherNode2
        = new DiscoveryNode("other2", "other2", buildNewFakeTransportAddress(), emptyMap(), singleton(Role.MASTER), Version.CURRENT);
    final VotingConfigExclusion otherNode2Exclusion = new VotingConfigExclusion(otherNode2);

    final ClusterState.Builder builder = ClusterState.builder(new ClusterName("cluster")).nodes(new Builder()
        .add(localNode).add(otherNode1).add(otherNode2).localNodeId(localNode.getId()));
    builder.metaData(MetaData.builder()
            .coordinationMetaData(CoordinationMetaData.builder().addVotingConfigExclusion(otherNode1Exclusion).build()));
    final ClusterState clusterState = builder.build();

    assertThat(makeRequest().resolveVotingConfigExclusionsAndCheckMaximum(clusterState, 3, "setting.name"),
            containsInAnyOrder(localNodeExclusion, otherNode2Exclusion));
    assertThat(makeRequest("_local").resolveVotingConfigExclusionsAndCheckMaximum(clusterState, 2, "setting.name"),
            contains(localNodeExclusion));

    assertThat(expectThrows(IllegalArgumentException.class,
        () -> makeRequest().resolveVotingConfigExclusionsAndCheckMaximum(clusterState, 2, "setting.name")).getMessage(),
        equalTo("add voting config exclusions request for [] would add [2] exclusions to the existing [1] which would exceed " +
            "the maximum of [2] set by [setting.name]"));
    assertThat(expectThrows(IllegalArgumentException.class,
        () -> makeRequest("_local").resolveVotingConfigExclusionsAndCheckMaximum(clusterState, 1, "setting.name")).getMessage(),
        equalTo("add voting config exclusions request for [_local] would add [1] exclusions to the existing [1] which would " +
            "exceed the maximum of [1] set by [setting.name]"));
}
 
Example 10
@Before
public void setupForTest() {
    final MockTransport transport = new MockTransport();
    transportService = transport.createTransportService(
        Settings.EMPTY,
        threadPool,
        TransportService.NOOP_TRANSPORT_INTERCEPTOR,
        boundTransportAddress -> localNode,
        null
    );

    new TransportClearVotingConfigExclusionsAction(
        transportService, clusterService, threadPool, new IndexNameExpressionResolver()); // registers action

    transportService.start();
    transportService.acceptIncomingRequests();

    final ClusterState.Builder builder = builder(new ClusterName("cluster"))
        .nodes(new Builder().add(localNode).add(otherNode1).add(otherNode2)
            .localNodeId(localNode.getId()).masterNodeId(localNode.getId()));
    builder.metaData(MetaData.builder()
            .coordinationMetaData(CoordinationMetaData.builder()
                    .addVotingConfigExclusion(otherNode1Exclusion)
                    .addVotingConfigExclusion(otherNode2Exclusion)
            .build()));
    setState(clusterService, builder);
}
 
Example 11
@Override
public ClusterState.Builder incrementVersion(ClusterState clusterState) {
    // generate cluster UUID deterministically for repeatable tests
    return ClusterState.builder(clusterState).incrementVersion().stateUUID(UUIDs.randomBase64UUID(random()));
}
 
Example 12
Source Project: crate   File: ClusterServiceUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static void setState(ClusterService clusterService, ClusterState.Builder clusterStateBuilder) {
    setState(clusterService, clusterStateBuilder.build());
}