Search in sources :

Example 1 with Streamable

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

the class ElasticsearchAssertions method tryCreateNewInstance.

private static Streamable tryCreateNewInstance(Streamable streamable) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    try {
        Class<? extends Streamable> clazz = streamable.getClass();
        Constructor<? extends Streamable> constructor = clazz.getConstructor();
        assertThat(constructor, Matchers.notNullValue());
        Streamable newInstance = constructor.newInstance();
        return newInstance;
    } catch (Exception e) {
        return null;
    }
}
Also used : Streamable(org.elasticsearch.common.io.stream.Streamable) ElasticsearchException(org.elasticsearch.ElasticsearchException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) ShardOperationFailedException(org.elasticsearch.action.ShardOperationFailedException)

Example 2 with Streamable

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

the class ElasticsearchAssertions method assertVersionSerializable.

public static void assertVersionSerializable(Version version, Streamable streamable, NamedWriteableRegistry namedWriteableRegistry) {
    try {
        Streamable newInstance = tryCreateNewInstance(streamable);
        if (newInstance == null) {
            // can't create a new instance - we never modify a
            return;
        // streamable that comes in.
        }
        if (streamable instanceof ActionRequest) {
            ((ActionRequest) streamable).validate();
        }
        BytesReference orig;
        try {
            orig = serialize(version, streamable);
        } catch (IllegalArgumentException e) {
            // Can't serialize with this version so skip this test.
            return;
        }
        StreamInput input = orig.streamInput();
        if (namedWriteableRegistry != null) {
            input = new NamedWriteableAwareStreamInput(input, namedWriteableRegistry);
        }
        input.setVersion(version);
        newInstance.readFrom(input);
        assertThat("Stream should be fully read with version [" + version + "] for streamable [" + streamable + "]", input.available(), equalTo(0));
        BytesReference newBytes = serialize(version, streamable);
        if (false == orig.equals(newBytes)) {
            // The bytes are different. That is a failure. Lets try to throw a useful exception for debugging.
            String message = "Serialization failed with version [" + version + "] bytes should be equal for streamable [" + streamable + "]";
            // If the bytes are different then comparing BytesRef's toStrings will show you *where* they are different
            assertEquals(message, orig.toBytesRef().toString(), newBytes.toBytesRef().toString());
            // They bytes aren't different. Very very weird.
            fail(message);
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to check serialization - version [" + version + "] for streamable [" + streamable + "]", ex);
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) ActionRequest(org.elasticsearch.action.ActionRequest) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) Streamable(org.elasticsearch.common.io.stream.Streamable) ElasticsearchException(org.elasticsearch.ElasticsearchException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) ShardOperationFailedException(org.elasticsearch.action.ShardOperationFailedException)

Example 3 with Streamable

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

the class ElasticsearchAssertionsTests method testAssertVersionSerializableIsOkWithIllegalArgumentException.

public void testAssertVersionSerializableIsOkWithIllegalArgumentException() {
    Version version = randomVersion(random());
    NamedWriteableRegistry registry = new NamedWriteableRegistry(emptyList());
    Streamable testStreamable = new TestStreamable();
    // Should catch the exception and do nothing.
    assertVersionSerializable(version, testStreamable, registry);
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) Version(org.elasticsearch.Version) VersionUtils.randomVersion(org.elasticsearch.test.VersionUtils.randomVersion) Streamable(org.elasticsearch.common.io.stream.Streamable)

Example 4 with Streamable

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

the class UpdateRequestTests method testNowInScript.

public void testNowInScript() throws IOException {
    Path genericConfigFolder = createTempDir();
    Settings baseSettings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).put(Environment.PATH_CONF_SETTING.getKey(), genericConfigFolder).build();
    Environment environment = new Environment(baseSettings);
    Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();
    scripts.put("ctx._source.update_timestamp = ctx._now", (vars) -> {
        Map<String, Object> vars2 = vars;
        @SuppressWarnings("unchecked") Map<String, Object> ctx = (Map<String, Object>) vars2.get("ctx");
        @SuppressWarnings("unchecked") Map<String, Object> source = (Map<String, Object>) ctx.get("_source");
        source.put("update_timestamp", ctx.get("_now"));
        return null;
    });
    scripts.put("ctx._timestamp = ctx._now", (vars) -> {
        @SuppressWarnings("unchecked") Map<String, Object> ctx = (Map<String, Object>) vars.get("ctx");
        ctx.put("_timestamp", ctx.get("_now"));
        return null;
    });
    ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(Collections.emptyList());
    ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections.singletonList(new MockScriptEngine("mock", scripts)));
    ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
    ScriptService scriptService = new ScriptService(baseSettings, environment, new ResourceWatcherService(baseSettings, null), scriptEngineRegistry, scriptContextRegistry, scriptSettings);
    Settings settings = settings(Version.CURRENT).build();
    UpdateHelper updateHelper = new UpdateHelper(settings, scriptService);
    // We just upsert one document with now() using a script
    IndexRequest indexRequest = new IndexRequest("test", "type1", "2").source(jsonBuilder().startObject().field("foo", "bar").endObject());
    {
        UpdateRequest updateRequest = new UpdateRequest("test", "type1", "2").upsert(indexRequest).script(new Script(ScriptType.INLINE, "mock", "ctx._source.update_timestamp = ctx._now", Collections.emptyMap())).scriptedUpsert(true);
        long nowInMillis = randomNonNegativeLong();
        // We simulate that the document is not existing yet
        GetResult getResult = new GetResult("test", "type1", "2", 0, false, null, null);
        UpdateHelper.Result result = updateHelper.prepare(new ShardId("test", "_na_", 0), updateRequest, getResult, () -> nowInMillis);
        Streamable action = result.action();
        assertThat(action, instanceOf(IndexRequest.class));
        IndexRequest indexAction = (IndexRequest) action;
        assertEquals(indexAction.sourceAsMap().get("update_timestamp"), nowInMillis);
    }
    {
        UpdateRequest updateRequest = new UpdateRequest("test", "type1", "2").upsert(indexRequest).script(new Script(ScriptType.INLINE, "mock", "ctx._timestamp = ctx._now", Collections.emptyMap())).scriptedUpsert(true);
        // We simulate that the document is not existing yet
        GetResult getResult = new GetResult("test", "type1", "2", 0, true, new BytesArray("{}"), null);
        UpdateHelper.Result result = updateHelper.prepare(new ShardId("test", "_na_", 0), updateRequest, getResult, () -> 42L);
        Streamable action = result.action();
        assertThat(action, instanceOf(IndexRequest.class));
    }
}
Also used : HashMap(java.util.HashMap) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetResult(org.elasticsearch.index.get.GetResult) ScriptService(org.elasticsearch.script.ScriptService) ShardId(org.elasticsearch.index.shard.ShardId) Function(java.util.function.Function) ScriptSettings(org.elasticsearch.script.ScriptSettings) MockScriptEngine(org.elasticsearch.script.MockScriptEngine) Streamable(org.elasticsearch.common.io.stream.Streamable) ScriptSettings(org.elasticsearch.script.ScriptSettings) Settings(org.elasticsearch.common.settings.Settings) Path(java.nio.file.Path) Script(org.elasticsearch.script.Script) BytesArray(org.elasticsearch.common.bytes.BytesArray) GetResult(org.elasticsearch.index.get.GetResult) ScriptContextRegistry(org.elasticsearch.script.ScriptContextRegistry) ScriptEngineRegistry(org.elasticsearch.script.ScriptEngineRegistry) Environment(org.elasticsearch.env.Environment) HashMap(java.util.HashMap) Map(java.util.Map) ResourceWatcherService(org.elasticsearch.watcher.ResourceWatcherService)

Aggregations

Streamable (org.elasticsearch.common.io.stream.Streamable)4 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ElasticsearchException (org.elasticsearch.ElasticsearchException)2 ShardOperationFailedException (org.elasticsearch.action.ShardOperationFailedException)2 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)2 ClusterBlockException (org.elasticsearch.cluster.block.ClusterBlockException)2 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Function (java.util.function.Function)1 Version (org.elasticsearch.Version)1 ActionRequest (org.elasticsearch.action.ActionRequest)1 IndexRequest (org.elasticsearch.action.index.IndexRequest)1 BytesArray (org.elasticsearch.common.bytes.BytesArray)1 BytesReference (org.elasticsearch.common.bytes.BytesReference)1 NamedWriteableAwareStreamInput (org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput)1 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)1 StreamInput (org.elasticsearch.common.io.stream.StreamInput)1 Settings (org.elasticsearch.common.settings.Settings)1