Java Code Examples for org.elasticsearch.cluster.ClusterState#version()

The following examples show how to use org.elasticsearch.cluster.ClusterState#version() . 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: Elasticsearch   File: ZenDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * In the case we follow an elected master the new cluster state needs to have the same elected master and
 * the new cluster state version needs to be equal or higher than our cluster state version.
 * If the first condition fails we reject the cluster state and throw an error.
 * If the second condition fails we ignore the cluster state.
 */
static boolean shouldIgnoreOrRejectNewClusterState(ESLogger logger, ClusterState currentState, ClusterState newClusterState) {
    if (currentState.nodes().masterNodeId() == null) {
        return false;
    }
    if (!currentState.nodes().masterNodeId().equals(newClusterState.nodes().masterNodeId())) {
        logger.warn("received a cluster state from a different master then the current one, rejecting (received {}, current {})", newClusterState.nodes().masterNode(), currentState.nodes().masterNode());
        throw new IllegalStateException("cluster state from a different master than the current one, rejecting (received " + newClusterState.nodes().masterNode() + ", current " + currentState.nodes().masterNode() + ")");
    } else if (newClusterState.version() < currentState.version()) {
        // if the new state has a smaller version, and it has the same master node, then no need to process it
        logger.debug("received a cluster state that has a lower version than the current one, ignoring (received {}, current {})", newClusterState.version(), currentState.version());
        return true;
    } else {
        return false;
    }
}
 
Example 2
private void performRemoteAction(ClusterState state, ShardRouting primary, DiscoveryNode node) {
    if (state.version() < request.routedBasedOnClusterVersion()) {
        logger.trace("failed to find primary [{}] for request [{}] despite sender thinking it would be here. Local cluster state "
                + "version [{}]] is older than on sending node (version [{}]), scheduling a retry...", request.shardId(), request,
            state.version(), request.routedBasedOnClusterVersion());
        retryBecauseUnavailable(request.shardId(), "failed to find primary as current cluster state with version ["
            + state.version() + "] is stale (expected at least [" + request.routedBasedOnClusterVersion() + "]");
        return;
    } else {
        // chasing the node with the active primary for a second hop requires that we are at least up-to-date with the current
        // cluster state version this prevents redirect loops between two nodes when a primary was relocated and the relocation
        // target is not aware that it is the active primary shard already.
        request.routedBasedOnClusterVersion(state.version());
    }
    if (logger.isTraceEnabled()) {
        logger.trace("send action [{}] on primary [{}] for request [{}] with cluster state version [{}] to [{}]", actionName,
            request.shardId(), request, state.version(), primary.currentNodeId());
    }
    setPhase(task, "rerouted");
    performAction(node, actionName, false, request);
}
 
Example 3
Source Project: Elasticsearch   File: JoinClusterAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
    logger.info("add node [{}] to cluster successfully", node);
    if (oldState.version() != newState.version()) {
        routingService.reroute("[" + node + "] added");
    }
    callback.onSuccess();
}
 
Example 4
Source Project: crate   File: GatewayMetaState.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates manifest and meta data on disk.
 *
 * @param newState new {@link ClusterState}
 * @param previousState previous {@link ClusterState}
 *
 * @throws WriteStateException if exception occurs. See also {@link WriteStateException#isDirty()}.
 */
protected void updateClusterState(ClusterState newState, ClusterState previousState)
        throws WriteStateException {
    MetaData newMetaData = newState.metaData();

    final AtomicClusterStateWriter writer = new AtomicClusterStateWriter(metaStateService, previousManifest);
    long globalStateGeneration = writeGlobalState(writer, newMetaData);
    Map<Index, Long> indexGenerations = writeIndicesMetadata(writer, newState, previousState);
    Manifest manifest = new Manifest(previousManifest.getCurrentTerm(), newState.version(), globalStateGeneration, indexGenerations);
    writeManifest(writer, manifest);

    previousManifest = manifest;
    previousClusterState = newState;
}
 
Example 5
Source Project: crate   File: MasterService.java    License: Apache License 2.0 5 votes vote down vote up
private void handleException(String summary, long startTimeNS, ClusterState newClusterState, Exception e) {
    TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(currentTimeInNanos() - startTimeNS)));
    final long version = newClusterState.version();
    final String stateUUID = newClusterState.stateUUID();
    final String fullState = newClusterState.toString();
    LOGGER.warn(() -> new ParameterizedMessage(
            "failed to publish updated cluster state in [{}]:\nversion [{}], uuid [{}], source [{}]\n{}",
            executionTime,
            version,
            stateUUID,
            summary,
            fullState),
        e);
    // TODO: do we want to call updateTask.onFailure here?
}
 
Example 6
public void testDiffSerializationFailure() {
    DeterministicTaskQueue deterministicTaskQueue =
        new DeterministicTaskQueue(Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "test").build(), random());
    final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    final DiscoveryNode localNode = new DiscoveryNode("localNode", buildNewFakeTransportAddress(), Version.CURRENT);
    final TransportService transportService = new CapturingTransport().createTransportService(
        Settings.EMPTY,
        deterministicTaskQueue.getThreadPool(),
        TransportService.NOOP_TRANSPORT_INTERCEPTOR,
        x -> localNode,
        clusterSettings
    );
    final PublicationTransportHandler handler = new PublicationTransportHandler(transportService,
        writableRegistry(), pu -> null, (pu, l) -> {});
    transportService.start();
    transportService.acceptIncomingRequests();

    final DiscoveryNode otherNode = new DiscoveryNode("otherNode", buildNewFakeTransportAddress(), Version.CURRENT);
    final ClusterState clusterState = CoordinationStateTests.clusterState(2L, 1L,
        DiscoveryNodes.builder().add(localNode).add(otherNode).localNodeId(localNode.getId()).build(),
        VotingConfiguration.EMPTY_CONFIG, VotingConfiguration.EMPTY_CONFIG, 0L);

    final ClusterState unserializableClusterState = new ClusterState(clusterState.version(),
        clusterState.stateUUID(), clusterState) {
        @Override
        public Diff<ClusterState> diff(ClusterState previousState) {
            return new Diff<ClusterState>() {
                @Override
                public ClusterState apply(ClusterState part) {
                    fail("this diff shouldn't be applied");
                    return part;
                }

                @Override
                public void writeTo(StreamOutput out) throws IOException {
                    throw new IOException("Simulated failure of diff serialization");
                }
            };
        }
    };

    ElasticsearchException e = expectThrows(ElasticsearchException.class, () ->
        handler.newPublicationContext(new ClusterChangedEvent("test", unserializableClusterState, clusterState)));
    assertNotNull(e.getCause());
    assertThat(e.getCause(), instanceOf(IOException.class));
    assertThat(e.getCause().getMessage(), containsString("Simulated failure of diff serialization"));
}