Search in sources :

Example 36 with StreamInput

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

the class PutIndexTemplateRequestTests method testPutIndexTemplateRequestSerializationXContent.

public void testPutIndexTemplateRequestSerializationXContent() throws IOException {
    PutIndexTemplateRequest request = new PutIndexTemplateRequest("foo");
    String mapping = YamlXContent.contentBuilder().startObject().field("foo", "bar").endObject().string();
    request.patterns(Collections.singletonList("foo"));
    request.mapping("bar", mapping, XContentType.YAML);
    assertNotEquals(mapping, request.mappings().get("bar"));
    assertEquals(XContentHelper.convertToJson(new BytesArray(mapping), false, XContentType.YAML), request.mappings().get("bar"));
    BytesStreamOutput out = new BytesStreamOutput();
    request.writeTo(out);
    StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
    PutIndexTemplateRequest serialized = new PutIndexTemplateRequest();
    serialized.readFrom(in);
    assertEquals(XContentHelper.convertToJson(new BytesArray(mapping), false, XContentType.YAML), serialized.mappings().get("bar"));
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) StreamInput(org.elasticsearch.common.io.stream.StreamInput) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 37 with StreamInput

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

the class GetFieldMappingsResponseTests method testSerialization.

public void testSerialization() throws IOException {
    Map<String, Map<String, Map<String, FieldMappingMetaData>>> mappings = new HashMap<>();
    FieldMappingMetaData fieldMappingMetaData = new FieldMappingMetaData("my field", new BytesArray("{}"));
    mappings.put("index", Collections.singletonMap("type", Collections.singletonMap("field", fieldMappingMetaData)));
    GetFieldMappingsResponse response = new GetFieldMappingsResponse(mappings);
    try (BytesStreamOutput out = new BytesStreamOutput()) {
        response.writeTo(out);
        GetFieldMappingsResponse serialized = new GetFieldMappingsResponse();
        try (StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes)) {
            serialized.readFrom(in);
            FieldMappingMetaData metaData = serialized.fieldMappings("index", "type", "field");
            assertNotNull(metaData);
            assertEquals(new BytesArray("{}"), metaData.getSource());
        }
    }
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) HashMap(java.util.HashMap) FieldMappingMetaData(org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Map(java.util.Map) HashMap(java.util.HashMap) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 38 with StreamInput

use of org.elasticsearch.common.io.stream.StreamInput 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)

Example 39 with StreamInput

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

the class BlobStoreFormatIT method randomCorruption.

protected void randomCorruption(BlobContainer blobContainer, String blobName) throws IOException {
    byte[] buffer = new byte[(int) blobContainer.listBlobsByPrefix(blobName).get(blobName).length()];
    long originalChecksum = checksum(buffer);
    try (InputStream inputStream = blobContainer.readBlob(blobName)) {
        Streams.readFully(inputStream, buffer);
    }
    do {
        int location = randomIntBetween(0, buffer.length - 1);
        buffer[location] = (byte) (buffer[location] ^ 42);
    } while (originalChecksum == checksum(buffer));
    // delete original before writing new blob
    blobContainer.deleteBlob(blobName);
    BytesArray bytesArray = new BytesArray(buffer);
    try (StreamInput stream = bytesArray.streamInput()) {
        blobContainer.writeBlob(blobName, stream, bytesArray.length());
    }
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) InputStream(java.io.InputStream) StreamInput(org.elasticsearch.common.io.stream.StreamInput)

Example 40 with StreamInput

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

the class TaskIdTests method roundTrip.

private TaskId roundTrip(TaskId taskId, int expectedSize) throws IOException {
    try (BytesStreamOutput out = new BytesStreamOutput()) {
        taskId.writeTo(out);
        BytesReference bytes = out.bytes();
        assertEquals(expectedSize, bytes.length());
        try (StreamInput in = bytes.streamInput()) {
            return TaskId.readFromStream(in);
        }
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) StreamInput(org.elasticsearch.common.io.stream.StreamInput) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Aggregations

StreamInput (org.elasticsearch.common.io.stream.StreamInput)183 BytesStreamOutput (org.elasticsearch.common.io.stream.BytesStreamOutput)146 Test (org.junit.Test)52 CrateUnitTest (io.crate.test.integration.CrateUnitTest)37 NamedWriteableAwareStreamInput (org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput)30 BytesArray (org.elasticsearch.common.bytes.BytesArray)24 Version (org.elasticsearch.Version)21 IOException (java.io.IOException)13 BytesReference (org.elasticsearch.common.bytes.BytesReference)10 UUID (java.util.UUID)9 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)9 Symbol (io.crate.analyze.symbol.Symbol)8 BytesRef (org.apache.lucene.util.BytesRef)8 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ShardId (org.elasticsearch.index.shard.ShardId)6 List (java.util.List)5 AliasFilter (org.elasticsearch.search.internal.AliasFilter)5 Aggregation (io.crate.analyze.symbol.Aggregation)4