Search in sources :

Example 6 with NamedWriteableAwareStreamInput

use of org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput in project elasticsearch by elastic.

the class AbstractStreamableTestCase method copyInstance.

/**
     * Round trip {@code instance} through binary serialization, setting the wire compatibility version to {@code version}.
     */
protected T copyInstance(T instance, Version version) throws IOException {
    try (BytesStreamOutput output = new BytesStreamOutput()) {
        output.setVersion(version);
        instance.writeTo(output);
        try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), getNamedWriteableRegistry())) {
            in.setVersion(version);
            T newInstance = createBlankInstance();
            newInstance.readFrom(in);
            return newInstance;
        }
    }
}
Also used : NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 7 with NamedWriteableAwareStreamInput

use of org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput in project elasticsearch by elastic.

the class ShardValidateQueryRequestTests method testSerialize50Request.

// BWC test for changes from #20916
public void testSerialize50Request() throws IOException {
    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest("indices");
    validateQueryRequest.query(QueryBuilders.termQuery("field", "value"));
    validateQueryRequest.rewrite(true);
    validateQueryRequest.explain(false);
    validateQueryRequest.types("type1", "type2");
    ShardValidateQueryRequest request = new ShardValidateQueryRequest(new ShardId("index", "foobar", 1), new AliasFilter(QueryBuilders.termQuery("filter_field", "value"), new String[] { "alias0", "alias1" }), validateQueryRequest);
    BytesArray requestBytes = new BytesArray(Base64.getDecoder().decode("AAVpbmRleAZmb29iYXIBAQdpbmRpY2VzBAR0ZXJtP4AAAAAFZmllbGQVBXZhbHVlAgV0eXBlMQV0eXBlMgIGYWxpYXMwBmFsaWFzMQABAA"));
    try (StreamInput in = new NamedWriteableAwareStreamInput(requestBytes.streamInput(), namedWriteableRegistry)) {
        in.setVersion(Version.V_5_0_0);
        ShardValidateQueryRequest readRequest = new ShardValidateQueryRequest();
        readRequest.readFrom(in);
        assertEquals(0, in.available());
        assertArrayEquals(request.filteringAliases().getAliases(), readRequest.filteringAliases().getAliases());
        expectThrows(IllegalStateException.class, () -> readRequest.filteringAliases().getQueryBuilder());
        assertArrayEquals(request.types(), readRequest.types());
        assertEquals(request.explain(), readRequest.explain());
        assertEquals(request.query(), readRequest.query());
        assertEquals(request.rewrite(), readRequest.rewrite());
        assertEquals(request.shardId(), readRequest.shardId());
        BytesStreamOutput output = new BytesStreamOutput();
        output.setVersion(Version.V_5_0_0);
        readRequest.writeTo(output);
        assertEquals(output.bytes().toBytesRef(), requestBytes.toBytesRef());
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) ShardValidateQueryRequest(org.elasticsearch.action.admin.indices.validate.query.ShardValidateQueryRequest) AliasFilter(org.elasticsearch.search.internal.AliasFilter) BytesArray(org.elasticsearch.common.bytes.BytesArray) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) ValidateQueryRequest(org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest) ShardValidateQueryRequest(org.elasticsearch.action.admin.indices.validate.query.ShardValidateQueryRequest) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 8 with NamedWriteableAwareStreamInput

use of org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput in project elasticsearch by elastic.

the class PublishClusterStateAction method handleIncomingClusterStateRequest.

protected void handleIncomingClusterStateRequest(BytesTransportRequest request, TransportChannel channel) throws IOException {
    Compressor compressor = CompressorFactory.compressor(request.bytes());
    StreamInput in = request.bytes().streamInput();
    try {
        if (compressor != null) {
            in = compressor.streamInput(in);
        }
        in = new NamedWriteableAwareStreamInput(in, namedWriteableRegistry);
        in.setVersion(request.version());
        synchronized (lastSeenClusterStateMutex) {
            final ClusterState incomingState;
            // If true we received full cluster state - otherwise diffs
            if (in.readBoolean()) {
                incomingState = ClusterState.readFrom(in, clusterStateSupplier.get().nodes().getLocalNode());
                logger.debug("received full cluster state version [{}] with size [{}]", incomingState.version(), request.bytes().length());
            } else if (lastSeenClusterState != null) {
                Diff<ClusterState> diff = ClusterState.readDiffFrom(in, lastSeenClusterState.nodes().getLocalNode());
                incomingState = diff.apply(lastSeenClusterState);
                logger.debug("received diff cluster state version [{}] with uuid [{}], diff size [{}]", incomingState.version(), incomingState.stateUUID(), request.bytes().length());
            } else {
                logger.debug("received diff for but don't have any local cluster state - requesting full state");
                throw new IncompatibleClusterStateVersionException("have no local cluster state");
            }
            // sanity check incoming state
            validateIncomingState(incomingState, lastSeenClusterState);
            pendingStatesQueue.addPending(incomingState);
            lastSeenClusterState = incomingState;
        }
    } finally {
        IOUtils.close(in);
    }
    channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) Diff(org.elasticsearch.cluster.Diff) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Compressor(org.elasticsearch.common.compress.Compressor) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) IncompatibleClusterStateVersionException(org.elasticsearch.cluster.IncompatibleClusterStateVersionException)

Example 9 with NamedWriteableAwareStreamInput

use of org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput in project elasticsearch by elastic.

the class ExplainRequestTests method testSerialize50Request.

// BWC test for changes from #20916
public void testSerialize50Request() throws IOException {
    ExplainRequest request = new ExplainRequest("index", "type", "id");
    request.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1.*" }, new String[] { "field2.*" }));
    request.filteringAlias(new AliasFilter(QueryBuilders.termQuery("filter_field", "value"), new String[] { "alias0", "alias1" }));
    request.preference("the_preference");
    request.query(QueryBuilders.termQuery("field", "value"));
    request.storedFields(new String[] { "field1", "field2" });
    request.routing("some_routing");
    BytesArray requestBytes = new BytesArray(Base64.getDecoder().decode("AAABBWluZGV4BHR5cGUCaWQBDHNvbWVfcm91dGluZwEOdGhlX3ByZWZlcmVuY2UEdGVybT" + "+AAAAABWZpZWxkFQV2YWx1ZQIGYWxpYXMwBmFsaWFzMQECBmZpZWxkMQZmaWVsZDIBAQEIZmllbGQxLioBCGZpZWxkMi4qAA"));
    try (StreamInput in = new NamedWriteableAwareStreamInput(requestBytes.streamInput(), namedWriteableRegistry)) {
        in.setVersion(Version.V_5_0_0);
        ExplainRequest readRequest = new ExplainRequest();
        readRequest.readFrom(in);
        assertEquals(0, in.available());
        assertArrayEquals(request.filteringAlias().getAliases(), readRequest.filteringAlias().getAliases());
        expectThrows(IllegalStateException.class, () -> readRequest.filteringAlias().getQueryBuilder());
        assertArrayEquals(request.storedFields(), readRequest.storedFields());
        assertEquals(request.preference(), readRequest.preference());
        assertEquals(request.query(), readRequest.query());
        assertEquals(request.routing(), readRequest.routing());
        assertEquals(request.fetchSourceContext(), readRequest.fetchSourceContext());
        BytesStreamOutput output = new BytesStreamOutput();
        output.setVersion(Version.V_5_0_0);
        readRequest.writeTo(output);
        assertEquals(output.bytes().toBytesRef(), requestBytes.toBytesRef());
    }
}
Also used : AliasFilter(org.elasticsearch.search.internal.AliasFilter) BytesArray(org.elasticsearch.common.bytes.BytesArray) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) ExplainRequest(org.elasticsearch.action.explain.ExplainRequest) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 10 with NamedWriteableAwareStreamInput

use of org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput in project elasticsearch by elastic.

the class ClusterStateDiffIT method testClusterStateDiffSerialization.

public void testClusterStateDiffSerialization() throws Exception {
    NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(ClusterModule.getNamedWriteables());
    DiscoveryNode masterNode = new DiscoveryNode("master", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    DiscoveryNode otherNode = new DiscoveryNode("other", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(masterNode).add(otherNode).localNodeId(masterNode.getId()).build();
    ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(discoveryNodes).build();
    ClusterState clusterStateFromDiffs = ClusterState.Builder.fromBytes(ClusterState.Builder.toBytes(clusterState), otherNode, namedWriteableRegistry);
    int iterationCount = randomIntBetween(10, 300);
    for (int iteration = 0; iteration < iterationCount; iteration++) {
        ClusterState previousClusterState = clusterState;
        ClusterState previousClusterStateFromDiffs = clusterStateFromDiffs;
        int changesCount = randomIntBetween(1, 4);
        ClusterState.Builder builder = null;
        for (int i = 0; i < changesCount; i++) {
            if (i > 0) {
                clusterState = builder.build();
            }
            switch(randomInt(4)) {
                case 0:
                    builder = randomNodes(clusterState);
                    break;
                case 1:
                    builder = randomRoutingTable(clusterState);
                    break;
                case 2:
                    builder = randomBlocks(clusterState);
                    break;
                case 3:
                    builder = randomClusterStateCustoms(clusterState);
                    break;
                case 4:
                    builder = randomMetaDataChanges(clusterState);
                    break;
                default:
                    throw new IllegalArgumentException("Shouldn't be here");
            }
        }
        clusterState = builder.incrementVersion().build();
        if (randomIntBetween(0, 10) < 1) {
            // Update cluster state via full serialization from time to time
            clusterStateFromDiffs = ClusterState.Builder.fromBytes(ClusterState.Builder.toBytes(clusterState), previousClusterStateFromDiffs.nodes().getLocalNode(), namedWriteableRegistry);
        } else {
            // Update cluster states using diffs
            Diff<ClusterState> diffBeforeSerialization = clusterState.diff(previousClusterState);
            BytesStreamOutput os = new BytesStreamOutput();
            diffBeforeSerialization.writeTo(os);
            byte[] diffBytes = BytesReference.toBytes(os.bytes());
            Diff<ClusterState> diff;
            try (StreamInput input = StreamInput.wrap(diffBytes)) {
                StreamInput namedInput = new NamedWriteableAwareStreamInput(input, namedWriteableRegistry);
                diff = ClusterState.readDiffFrom(namedInput, previousClusterStateFromDiffs.nodes().getLocalNode());
                clusterStateFromDiffs = diff.apply(previousClusterStateFromDiffs);
            }
        }
        try {
            // Check non-diffable elements
            assertThat(clusterStateFromDiffs.version(), equalTo(clusterState.version()));
            assertThat(clusterStateFromDiffs.stateUUID(), equalTo(clusterState.stateUUID()));
            // Check nodes
            assertThat(clusterStateFromDiffs.nodes().getNodes(), equalTo(clusterState.nodes().getNodes()));
            assertThat(clusterStateFromDiffs.nodes().getLocalNodeId(), equalTo(previousClusterStateFromDiffs.nodes().getLocalNodeId()));
            assertThat(clusterStateFromDiffs.nodes().getNodes(), equalTo(clusterState.nodes().getNodes()));
            for (ObjectCursor<String> node : clusterStateFromDiffs.nodes().getNodes().keys()) {
                DiscoveryNode node1 = clusterState.nodes().get(node.value);
                DiscoveryNode node2 = clusterStateFromDiffs.nodes().get(node.value);
                assertThat(node1.getVersion(), equalTo(node2.getVersion()));
                assertThat(node1.getAddress(), equalTo(node2.getAddress()));
                assertThat(node1.getAttributes(), equalTo(node2.getAttributes()));
            }
            // Check routing table
            assertThat(clusterStateFromDiffs.routingTable().version(), equalTo(clusterState.routingTable().version()));
            assertThat(clusterStateFromDiffs.routingTable().indicesRouting(), equalTo(clusterState.routingTable().indicesRouting()));
            // Check cluster blocks
            assertThat(clusterStateFromDiffs.blocks().global(), equalTo(clusterStateFromDiffs.blocks().global()));
            assertThat(clusterStateFromDiffs.blocks().indices(), equalTo(clusterStateFromDiffs.blocks().indices()));
            assertThat(clusterStateFromDiffs.blocks().disableStatePersistence(), equalTo(clusterStateFromDiffs.blocks().disableStatePersistence()));
            // Check metadata
            assertThat(clusterStateFromDiffs.metaData().version(), equalTo(clusterState.metaData().version()));
            assertThat(clusterStateFromDiffs.metaData().clusterUUID(), equalTo(clusterState.metaData().clusterUUID()));
            assertThat(clusterStateFromDiffs.metaData().transientSettings(), equalTo(clusterState.metaData().transientSettings()));
            assertThat(clusterStateFromDiffs.metaData().persistentSettings(), equalTo(clusterState.metaData().persistentSettings()));
            assertThat(clusterStateFromDiffs.metaData().indices(), equalTo(clusterState.metaData().indices()));
            assertThat(clusterStateFromDiffs.metaData().templates(), equalTo(clusterState.metaData().templates()));
            assertThat(clusterStateFromDiffs.metaData().customs(), equalTo(clusterState.metaData().customs()));
            assertThat(clusterStateFromDiffs.metaData().equalsAliases(clusterState.metaData()), is(true));
            // JSON Serialization test - make sure that both states produce similar JSON
            assertNull(differenceBetweenMapsIgnoringArrayOrder(convertToMap(clusterStateFromDiffs), convertToMap(clusterState)));
            // Smoke test - we cannot compare bytes to bytes because some elements might get serialized in different order
            // however, serialized size should remain the same
            assertThat(ClusterState.Builder.toBytes(clusterStateFromDiffs).length, equalTo(ClusterState.Builder.toBytes(clusterState).length));
        } catch (AssertionError error) {
            logger.error("Cluster state:\n{}\nCluster state from diffs:\n{}", clusterState.toString(), clusterStateFromDiffs.toString());
            throw error;
        }
    }
    logger.info("Final cluster state:[{}]", clusterState.toString());
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes)

Aggregations

NamedWriteableAwareStreamInput (org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput)28 StreamInput (org.elasticsearch.common.io.stream.StreamInput)27 BytesStreamOutput (org.elasticsearch.common.io.stream.BytesStreamOutput)23 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)9 AliasFilter (org.elasticsearch.search.internal.AliasFilter)5 IOException (java.io.IOException)4 BytesArray (org.elasticsearch.common.bytes.BytesArray)4 Version (org.elasticsearch.Version)3 BytesReference (org.elasticsearch.common.bytes.BytesReference)3 ShardId (org.elasticsearch.index.shard.ShardId)3 ArrayList (java.util.ArrayList)2 ShardValidateQueryRequest (org.elasticsearch.action.admin.indices.validate.query.ShardValidateQueryRequest)2 ValidateQueryRequest (org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest)2 ExplainRequest (org.elasticsearch.action.explain.ExplainRequest)2 ClusterState (org.elasticsearch.cluster.ClusterState)2 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)2 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)2 AllocateEmptyPrimaryAllocationCommand (org.elasticsearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand)2 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)2 SearchModule (org.elasticsearch.search.SearchModule)2