Class ThreadContext
- All Implemented Interfaces:
Writeable,TraceContext
ThreadContext associated with. Threads spawned from a ThreadPool
have out of the box support for ThreadContext and all threads spawned will inherit the ThreadContext from the thread
that it is forking from.". Network calls will also preserve the senders headers automatically.
Consumers of ThreadContext usually don't need to interact with adding or stashing contexts. Every elasticsearch thread is managed by
a thread pool or executor being responsible for stashing and restoring the threads context. For instance if a network request is
received, all headers are deserialized from the network and directly added as the headers of the threads ThreadContext
(see readHeaders(StreamInput). In order to not modify the context that is currently active on this thread the network code
uses a try/with pattern to stash it's current context, read headers into a fresh one and once the request is handled or a handler thread
is forked (which in turn inherits the context) it restores the previous context. For instance:
// current context is stashed and replaced with a default context
try (StoredContext context = threadContext.stashContext()) {
threadContext.readHeaders(in); // read headers into current context
if (fork) {
threadPool.execute(() -> request.handle()); // inherits context
} else {
request.handle();
}
}
// previous context is restored on StoredContext#close()
-
Nested Class Summary
Nested ClassesNested classes/interfaces inherited from interface org.elasticsearch.common.io.stream.Writeable
Writeable.Reader<V>, Writeable.Writer<V> -
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddResponseHeader(String key, String value) Add thevaluefor the specifiedkey.voidAdd thevaluefor the specifiedkeywith the specifieduniqueValueused for de-duplication.buildDefaultHeaders(Settings settings) Captures the current thread context as writeable, allowing it to be serialized out laterWhen using aTracer, sometimes you need to start a span completely unrelated to any current span.voidcopyHeaders(Iterable<Map.Entry<String, String>> headers) Copies all header key, value pairs into the current contextReturns the header for the given key ornullif not presentgetHeaderOrDefault(String key, String defaultValue) Returns the header for the given key or defaultValue if not presentReturns all of the request headers from the thread's context.
Be advised, headers might contain credentials. In order to avoid storing, and erroneously exposing, such headers, it is recommended to instead store security headers that prove the credentials have been verified successfully, and which are internal to the system, in the sense that they cannot be sent by the clients.Returns the request headers, without the default headersGet a copy of all response headers.<T> TgetTransient(String key) Returns a transient header object ornullif there is no header for the given keyReturns unmodifiable copy of all transient headers.booleanbooleanReturns true if the current context is the default context.booleanReturnstrueiff this context is a system contextvoidMarks this thread context as an internal system context.Removes the current context and replaces it with a completely empty default context, detaching execution entirely from the calling context.Removes the current context and replaces it with a completely empty system context, detaching execution entirely from the calling context.newRestorableContext(boolean preserveResponseHeaders) Returns a supplier that gathers anewStoredContextPreservingResponseHeaders()and restores it once the returned supplier is invoked.Just likestashContext()but no default context is set.newStoredContext(Collection<String> transientHeadersToClear, Collection<String> requestHeadersToClear) Just likestashContext()but no default context is set.Just likestashContext()but no default context is set and the response headers of the restore thread will be preserved.newStoredContextPreservingResponseHeaders(Collection<String> transientHeadersToClear, Collection<String> requestHeadersToClear) Just likenewStoredContext(Collection, Collection)but all headers are restored to original, except ofresponseHeaderswhich will be preserved from the restore thread.When using aTracerto capture activity in Elasticsearch, when a parent span is already in progress, it is necessary to start a new context before beginning a child span.preserveContext(Runnable command) Saves the current thread context and wraps command in a Runnable that restores that context before running command.preserveContextWithTracing(Runnable command) Saves the current thread context and wraps command in a Runnable that restores that context before running command.voidPuts a header into the contextvoidPuts all of the given headers into this contextvoidputTransient(String key, Object value) Puts a transient header object into this contextvoidReads the headers from the stream into the current contextrestoreExistingContext(ThreadContext.StoredContext existingContext) Capture the current context and then restore the given context, returning aThreadContext.StoredContextthat reverts back to the current context again.voidRemove unwanted and unneeded headers from the thread context.voidvoidstashAndMergeHeaders(Map<String, String> headers) Removes the current context and resets a new context that contains a merge of the current headers and the given headers.Removes the current context and resets a default context except for headers involved in task tracing.stashContextPreservingRequestHeaders(String... requestHeaders) stashContextPreservingRequestHeaders(Set<String> requestHeaders) Just likestashContext()but preserves request headers specified viarequestHeaders, if these exist in the context before stashing.stashWithOrigin(String origin) Removes the current context and resets a default context marked with as originating from the supplied string.static RunnableUnwraps a command that was previously wrapped bypreserveContext(Runnable).wrapRestorable(ThreadContext.StoredContext storedContext) Same asnewRestorableContext(boolean)but wraps an existing context to restore.voidwriteTo(StreamOutput out) Write this into the StreamOutput.
-
Field Details
-
PREFIX
- See Also:
-
DEFAULT_HEADERS_SETTING
-
ACTION_ORIGIN_TRANSIENT_NAME
Name for theoriginattribute.- See Also:
-
-
Constructor Details
-
ThreadContext
Creates a new ThreadContext instance- Parameters:
settings- the settings to read the default request headers from
-
-
Method Details
-
stashContext
Removes the current context and resets a default context except for headers involved in task tracing. The removed context can be restored by closing the returnedThreadContext.StoredContext.- Returns:
- a stored context that will restore the current context to its state at the point this method was called
-
stashContextPreservingRequestHeaders
Just likestashContext()but preserves request headers specified viarequestHeaders, if these exist in the context before stashing. -
stashContextPreservingRequestHeaders
-
newEmptyContext
Removes the current context and replaces it with a completely empty default context, detaching execution entirely from the calling context. The calling context can be restored by closing the returnedThreadContext.StoredContext. Similar tostashContext()except that this method does not even preserve tracing-related headers. -
newEmptySystemContext
Removes the current context and replaces it with a completely empty system context, detaching execution entirely from the calling context. The calling context can be restored by closing the returnedThreadContext.StoredContext. Similar tostashContext()except that this method does not even preserve tracing-related headers. -
newTraceContext
When using aTracerto capture activity in Elasticsearch, when a parent span is already in progress, it is necessary to start a new context before beginning a child span. This method creates a context, moving tracing-related fields to different names so that a new child span can be started. This child span will pick up the moved fields and use them to establish the parent-child relationship.- Returns:
- a stored context, which can be restored when this context is no longer needed.
-
hasTraceContext
public boolean hasTraceContext() -
clearTraceContext
When using aTracer, sometimes you need to start a span completely unrelated to any current span. In order to avoid any parent/child relationship being created, this method creates a new context that clears all the tracing fields.- Returns:
- a stored context, which can be restored when this context is no longer needed.
-
captureAsWriteable
Captures the current thread context as writeable, allowing it to be serialized out later -
stashWithOrigin
Removes the current context and resets a default context marked with as originating from the supplied string. The removed context can be restored by closing the returnedThreadContext.StoredContext. Callers should be careful to save the current context before calling this method and restore it any listeners, likely withContextPreservingActionListener. UseOriginSettingClientwhich can be used to do this automatically.Without security the origin is ignored, but security uses it to authorize actions that are made up of many sub-actions. These actions call
stashWithOrigin(java.lang.String)before performing on behalf of a user that should be allowed even if the user doesn't have permission to perform those actions on their own.For example, a user might not have permission to GET from the tasks index but the tasks API will perform a get on their behalf using this method if it can't find the task in memory.
-
stashAndMergeHeaders
Removes the current context and resets a new context that contains a merge of the current headers and the given headers. The removed context can be restored when closing the returnedThreadContext.StoredContext. The merge strategy is that headers that are already existing are preserved unless they are defaults. -
newStoredContextPreservingResponseHeaders
Just likestashContext()but no default context is set and the response headers of the restore thread will be preserved. -
restoreExistingContext
public ThreadContext.StoredContext restoreExistingContext(ThreadContext.StoredContext existingContext) Capture the current context and then restore the given context, returning aThreadContext.StoredContextthat reverts back to the current context again. Equivalent to usingnewStoredContext()and then callingexistingContext.restore(). -
newStoredContext
Just likestashContext()but no default context is set. -
newStoredContext
public ThreadContext.StoredContext newStoredContext(Collection<String> transientHeadersToClear, Collection<String> requestHeadersToClear) Just likestashContext()but no default context is set. Instead, thetransientHeadersToClearargument can be used to clear specific transient headers in the new context andrequestHeadersToClearcan be used to clear specific request headers. All original headers (without theresponseHeaders) are restored by closing the returnedThreadContext.StoredContext. -
newStoredContextPreservingResponseHeaders
public ThreadContext.StoredContext newStoredContextPreservingResponseHeaders(Collection<String> transientHeadersToClear, Collection<String> requestHeadersToClear) Just likenewStoredContext(Collection, Collection)but all headers are restored to original, except ofresponseHeaderswhich will be preserved from the restore thread. -
newRestorableContext
Returns a supplier that gathers anewStoredContextPreservingResponseHeaders()and restores it once the returned supplier is invoked. The context returned from the supplier is a stored version of the suppliers callers context that should be restored once the originally gathered context is not needed anymore. For instance this method should be used like this:Supplier<ThreadContext.StoredContext> restorable = context.newRestorableContext(true); new Thread() { public void run() { try (ThreadContext.StoredContext ctx = restorable.get()) { // execute with the parents context and restore the threads context afterwards } } }.start();- Parameters:
preserveResponseHeaders- if set totruethe response headers of the restore thread will be preserved.- Returns:
- a restorable context supplier
-
wrapRestorable
public Supplier<ThreadContext.StoredContext> wrapRestorable(ThreadContext.StoredContext storedContext) Same asnewRestorableContext(boolean)but wraps an existing context to restore.- Parameters:
storedContext- the context to restore
-
writeTo
Description copied from interface:WriteableWrite this into the StreamOutput.- Specified by:
writeToin interfaceWriteable- Throws:
IOException
-
readHeaders
Reads the headers from the stream into the current context- Throws:
IOException
-
setHeaders
-
readHeadersFromStream
public static Tuple<Map<String,String>, readHeadersFromStreamMap<String, Set<String>>> (StreamInput in) throws IOException - Throws:
IOException
-
getHeader
Returns the header for the given key ornullif not present- Specified by:
getHeaderin interfaceTraceContext
-
getHeaderOrDefault
Returns the header for the given key or defaultValue if not present -
getHeaders
Returns all of the request headers from the thread's context.
Be advised, headers might contain credentials. In order to avoid storing, and erroneously exposing, such headers, it is recommended to instead store security headers that prove the credentials have been verified successfully, and which are internal to the system, in the sense that they cannot be sent by the clients. -
getRequestHeadersOnly
Returns the request headers, without the default headers -
getResponseHeaders
Get a copy of all response headers.- Returns:
- Never
null.
-
copyHeaders
Copies all header key, value pairs into the current context -
putHeader
Puts a header into the context- Specified by:
putHeaderin interfaceTraceContext
-
putHeader
Puts all of the given headers into this context -
setErrorTraceTransportHeader
-
putTransient
Puts a transient header object into this context- Specified by:
putTransientin interfaceTraceContext
-
getTransient
Returns a transient header object ornullif there is no header for the given key- Specified by:
getTransientin interfaceTraceContext
-
getTransientHeaders
Returns unmodifiable copy of all transient headers. -
addResponseHeader
Add thevaluefor the specifiedkey. Any duplicatevalueis ignored.- Parameters:
key- the header namevalue- the header value
-
addResponseHeader
Add thevaluefor the specifiedkeywith the specifieduniqueValueused for de-duplication. Any duplicatevalueafter applyinguniqueValueis ignored.- Parameters:
key- the header namevalue- the header valueuniqueValue- the function that produces de-duplication values
-
preserveContext
Saves the current thread context and wraps command in a Runnable that restores that context before running command. Ifcommandhas already been passed through this method then it is returned unaltered rather than wrapped twice. -
preserveContextWithTracing
Saves the current thread context and wraps command in a Runnable that restores that context before running command. Also starts a new tracing context durin executing. Ifcommandhas already been wrapped then it is returned unaltered. -
unwrap
Unwraps a command that was previously wrapped bypreserveContext(Runnable). -
isDefaultContext
public boolean isDefaultContext()Returns true if the current context is the default context. -
markAsSystemContext
public void markAsSystemContext()Marks this thread context as an internal system context. This signals that actions in this context are issued by the system itself rather than by a user action. -
isSystemContext
public boolean isSystemContext()Returnstrueiff this context is a system context -
sanitizeHeaders
public void sanitizeHeaders()Remove unwanted and unneeded headers from the thread context. Does not store prior context. -
buildDefaultHeaders
-