Search in sources :

Example 11 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class ESTestCase method resetDeprecationLogger.

/**
     * Reset the deprecation logger by removing the current thread context, and setting a new thread context if {@code setNewThreadContext}
     * is set to {@code true} and otherwise clearing the current thread context.
     *
     * @param setNewThreadContext whether or not to attach a new thread context to the deprecation logger
     */
private void resetDeprecationLogger(final boolean setNewThreadContext) {
    // "clear" current warning headers by setting a new ThreadContext
    DeprecationLogger.removeThreadContext(this.threadContext);
    try {
        this.threadContext.close();
    // catch IOException to avoid that call sites have to deal with it. It is only declared because this class implements Closeable
    // but it is impossible that this implementation will ever throw an IOException.
    } catch (IOException ex) {
        throw new AssertionError("IOException thrown while closing deprecation logger's thread context", ex);
    }
    if (setNewThreadContext) {
        this.threadContext = new ThreadContext(Settings.EMPTY);
        DeprecationLogger.setThreadContext(this.threadContext);
    } else {
        this.threadContext = null;
    }
}
Also used : ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException)

Example 12 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class DeprecationLogger method deprecated.

/**
     * Logs a deprecated message to the deprecation log, as well as to the local {@link ThreadContext}.
     *
     * @param threadContexts The node's {@link ThreadContext} (outside of concurrent tests, this should only ever have one context).
     * @param message The deprecation message.
     * @param params The parameters used to fill in the message, if any exist.
     */
@SuppressLoggerChecks(reason = "safely delegates to logger")
void deprecated(final Set<ThreadContext> threadContexts, final String message, final Object... params) {
    final Iterator<ThreadContext> iterator = threadContexts.iterator();
    if (iterator.hasNext()) {
        final String formattedMessage = LoggerMessageFormat.format(message, params);
        final String warningHeaderValue = formatWarning(formattedMessage);
        assert WARNING_HEADER_PATTERN.matcher(warningHeaderValue).matches();
        assert extractWarningValueFromWarningHeader(warningHeaderValue).equals(escape(formattedMessage));
        while (iterator.hasNext()) {
            try {
                final ThreadContext next = iterator.next();
                next.addResponseHeader("Warning", warningHeaderValue, DeprecationLogger::extractWarningValueFromWarningHeader);
            } catch (final IllegalStateException e) {
            // ignored; it should be removed shortly
            }
        }
        logger.warn(formattedMessage);
    } else {
        logger.warn(message, params);
    }
}
Also used : ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) SuppressLoggerChecks(org.elasticsearch.common.SuppressLoggerChecks)

Example 13 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class NetworkModuleTests method testRegisterInterceptor.

public void testRegisterInterceptor() {
    Settings settings = Settings.builder().put(NetworkModule.HTTP_ENABLED.getKey(), false).put(NetworkModule.TRANSPORT_TYPE_KEY, "local").build();
    AtomicInteger called = new AtomicInteger(0);
    TransportInterceptor interceptor = new TransportInterceptor() {

        @Override
        public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor, boolean forceExecution, TransportRequestHandler<T> actualHandler) {
            called.incrementAndGet();
            if ("foo/bar/boom".equals(action)) {
                assertTrue(forceExecution);
            } else {
                assertFalse(forceExecution);
            }
            return actualHandler;
        }
    };
    NetworkModule module = newNetworkModule(settings, false, new NetworkPlugin() {

        @Override
        public List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry, ThreadContext threadContext) {
            assertNotNull(threadContext);
            return Collections.singletonList(interceptor);
        }
    });
    TransportInterceptor transportInterceptor = module.getTransportInterceptor();
    assertEquals(0, called.get());
    transportInterceptor.interceptHandler("foo/bar/boom", null, true, null);
    assertEquals(1, called.get());
    transportInterceptor.interceptHandler("foo/baz/boom", null, false, null);
    assertEquals(2, called.get());
    assertTrue(transportInterceptor instanceof NetworkModule.CompositeTransportInterceptor);
    assertEquals(((NetworkModule.CompositeTransportInterceptor) transportInterceptor).transportInterceptors.size(), 1);
    assertSame(((NetworkModule.CompositeTransportInterceptor) transportInterceptor).transportInterceptors.get(0), interceptor);
    NullPointerException nullPointerException = expectThrows(NullPointerException.class, () -> {
        newNetworkModule(settings, false, new NetworkPlugin() {

            @Override
            public List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry, ThreadContext threadContext) {
                assertNotNull(threadContext);
                return Collections.singletonList(null);
            }
        });
    });
    assertEquals("interceptor must not be null", nullPointerException.getMessage());
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) TransportInterceptor(org.elasticsearch.transport.TransportInterceptor) TransportRequest(org.elasticsearch.transport.TransportRequest) TransportRequestHandler(org.elasticsearch.transport.TransportRequestHandler) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) List(java.util.List) Settings(org.elasticsearch.common.settings.Settings)

Example 14 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class DeprecationLoggerTests method testAddsCombinedHeaderWithThreadContext.

public void testAddsCombinedHeaderWithThreadContext() throws IOException {
    try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
        final Set<ThreadContext> threadContexts = Collections.singleton(threadContext);
        final String param = randomAsciiOfLengthBetween(1, 5);
        logger.deprecated(threadContexts, "A simple message [{}]", param);
        final String second = randomAsciiOfLengthBetween(1, 10);
        logger.deprecated(threadContexts, second);
        final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders();
        assertEquals(1, responseHeaders.size());
        final List<String> responses = responseHeaders.get("Warning");
        assertEquals(2, responses.size());
        assertThat(responses.get(0), warningValueMatcher);
        assertThat(responses.get(0), containsString("\"A simple message [" + param + "]\""));
        assertThat(responses.get(1), warningValueMatcher);
        assertThat(responses.get(1), containsString("\"" + second + "\""));
    }
}
Also used : ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) List(java.util.List) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 15 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class DeprecationLoggerTests method testIgnoresClosedThreadContext.

public void testIgnoresClosedThreadContext() throws IOException {
    ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
    Set<ThreadContext> threadContexts = new HashSet<>(1);
    threadContexts.add(threadContext);
    threadContext.close();
    logger.deprecated(threadContexts, "Ignored logger message");
    assertTrue(threadContexts.contains(threadContext));
}
Also used : ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) HashSet(java.util.HashSet)

Aggregations

ThreadContext (org.elasticsearch.common.util.concurrent.ThreadContext)33 Matchers.containsString (org.hamcrest.Matchers.containsString)15 IOException (java.io.IOException)12 FakeRestRequest (org.elasticsearch.test.rest.FakeRestRequest)12 NodeClient (org.elasticsearch.client.node.NodeClient)8 BytesArray (org.elasticsearch.common.bytes.BytesArray)8 List (java.util.List)7 ActionListener (org.elasticsearch.action.ActionListener)4 Before (org.junit.Before)4 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Settings (org.elasticsearch.common.settings.Settings)3 TransportAddress (org.elasticsearch.common.transport.TransportAddress)3 HttpServerTransport (org.elasticsearch.http.HttpServerTransport)3 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)2 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Strings.collectionToDelimitedString (org.elasticsearch.common.Strings.collectionToDelimitedString)2