Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.common.io.stream;

import org.opensearch.common.annotation.InternalApi;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.Writeable;

import java.io.IOException;
import java.util.Base64;

/**
* Utility for round-tripping a {@link Writeable} through its binary wire format encoded as a
* Base64 string. This is useful when a {@link Writeable} needs to travel over a channel that only
* carries strings (for example a {@code ThreadContext} response header), where the binary form is
* both cheaper to produce/consume than JSON and more compact once Base64-encoded.
*
* @opensearch.internal
*/
@InternalApi
public final class WriteableBase64 {

private WriteableBase64() {}

/**
* Serializes a {@link Writeable} to its binary wire format and Base64-encodes the result.
*
* @param writeable the object to serialize
* @return a Base64-encoded string of the object's binary representation
* @throws IOException if serialization fails
*/
public static String encode(Writeable writeable) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
writeable.writeTo(out);
byte[] bytes = BytesReference.toBytes(out.bytes());
return Base64.getEncoder().encodeToString(bytes);
}
}

/**
* Decodes a Base64 string produced by {@link #encode(Writeable)} back into an object using the
* supplied reader.
*
* @param encoded the Base64-encoded string
* @param reader reconstructs the object from a {@link StreamInput} (for example
* {@code MyType::readFromStream} or {@code MyType::new})
* @param <T> the type produced by {@code reader}
* @return the deserialized object
* @throws IOException if deserialization fails
* @throws IllegalArgumentException if the input is not valid Base64
*/
public static <T> T decode(String encoded, Writeable.Reader<T> reader) throws IOException {
byte[] bytes = Base64.getDecoder().decode(encoded);
try (StreamInput in = StreamInput.wrap(bytes)) {
return reader.read(in);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,7 @@ public void apply(Settings value, Settings current, Settings previous) {
ShardIndexingPressureMemoryManager.MAX_OUTSTANDING_REQUESTS,
IndexingPressure.MAX_INDEXING_BYTES,
TaskResourceTrackingService.TASK_RESOURCE_TRACKING_ENABLED,
TaskResourceTrackingService.BINARY_RESOURCE_USAGE_HEADER_ENABLED,
TaskManager.TASK_RESOURCE_CONSUMERS_ENABLED,
TopNSearchTasksLogger.LOG_TOP_QUERIES_SIZE_SETTING,
TopNSearchTasksLogger.LOG_TOP_QUERIES_FREQUENCY_SETTING,
Expand Down
3 changes: 2 additions & 1 deletion server/src/main/java/org/opensearch/node/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,8 @@ protected Node(final Environment initialEnvironment, Collection<PluginInfo> clas
final TaskResourceTrackingService taskResourceTrackingService = new TaskResourceTrackingService(
settings,
clusterService.getClusterSettings(),
threadPool
threadPool,
clusterService
);

final SearchRequestStats searchRequestStats = new SearchRequestStats(clusterService.getClusterSettings());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.opensearch.ExceptionsHelper;
import org.opensearch.Version;
import org.opensearch.action.search.SearchShardTask;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.inject.Inject;
import org.opensearch.common.io.stream.WriteableBase64;
import org.opensearch.common.settings.ClusterSettings;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.settings.Settings;
Expand Down Expand Up @@ -62,21 +66,49 @@ public class TaskResourceTrackingService implements RunnableTaskExecutionListene
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
// Kill-switch for emitting the Base64 binary TASK_RESOURCE_USAGE response header. When false,
// data nodes always emit the legacy JSON header. The consumer always falls back to JSON regardless.
public static final Setting<Boolean> BINARY_RESOURCE_USAGE_HEADER_ENABLED = Setting.boolSetting(
"task_resource_tracking.binary_header.enabled",
true,
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
public static final String TASK_ID = "TASK_ID";
public static final String TASK_RESOURCE_USAGE = "TASK_RESOURCE_USAGE";

// First OpenSearch version that emits and parses the Base64 binary form of the
// TASK_RESOURCE_USAGE response header. Coordinators older than this only understand JSON.
static final Version BINARY_RESOURCE_USAGE_HEADER_VERSION = Version.V_3_8_0;

private static final ThreadMXBean threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();

private final ConcurrentMapLong<Task> resourceAwareTasks = ConcurrentCollections.newConcurrentMapLongWithAggressiveConcurrency();
private final List<TaskCompletionListener> taskCompletionListeners = new ArrayList<>();
private final ThreadPool threadPool;
private final ClusterService clusterService;
private volatile boolean taskResourceTrackingEnabled;
private volatile boolean binaryResourceUsageHeaderEnabled;

@Inject
public TaskResourceTrackingService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool) {
public TaskResourceTrackingService(
Settings settings,
ClusterSettings clusterSettings,
ThreadPool threadPool,
ClusterService clusterService
) {
this.taskResourceTrackingEnabled = TASK_RESOURCE_TRACKING_ENABLED.get(settings);
this.binaryResourceUsageHeaderEnabled = BINARY_RESOURCE_USAGE_HEADER_ENABLED.get(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
clusterSettings.addSettingsUpdateConsumer(TASK_RESOURCE_TRACKING_ENABLED, this::setTaskResourceTrackingEnabled);
clusterSettings.addSettingsUpdateConsumer(BINARY_RESOURCE_USAGE_HEADER_ENABLED, this::setBinaryResourceUsageHeaderEnabled);
}

// Without ClusterService, writeTaskResourceUsage cannot verify the coordinator's version
// and will always emit the legacy JSON header. Forgoes the binary CPU win but is rolling-upgrade safe.
public TaskResourceTrackingService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool) {
this(settings, clusterSettings, threadPool, null);
}

public void setTaskResourceTrackingEnabled(boolean taskResourceTrackingEnabled) {
Expand All @@ -87,6 +119,14 @@ public boolean isTaskResourceTrackingEnabled() {
return taskResourceTrackingEnabled;
}

public void setBinaryResourceUsageHeaderEnabled(boolean binaryResourceUsageHeaderEnabled) {
this.binaryResourceUsageHeaderEnabled = binaryResourceUsageHeaderEnabled;
}

public boolean isBinaryResourceUsageHeaderEnabled() {
Comment thread
cwperks marked this conversation as resolved.
Resolved
return binaryResourceUsageHeaderEnabled;
}

public boolean isTaskResourceTrackingSupported() {
return threadMXBean.isThreadAllocatedMemorySupported() && threadMXBean.isThreadAllocatedMemoryEnabled();
}
Expand Down Expand Up @@ -321,13 +361,38 @@ public void writeTaskResourceUsage(SearchShardTask task, String nodeId) {
)
)
.build();
String headerValue = canCoordinatorReadBinaryHeader(task)
? WriteableBase64.encode(taskResourceInfo)
: taskResourceInfo.toString();
// Remove the existing TASK_RESOURCE_USAGE header since it would have come from an earlier phase in the same request.
threadPool.getThreadContext().updateResponseHeader(TASK_RESOURCE_USAGE, taskResourceInfo.toString());
threadPool.getThreadContext().updateResponseHeader(TASK_RESOURCE_USAGE, headerValue);
} catch (Exception e) {
logger.debug("Error during writing task resource usage: ", e);
}
}

// Returns true only with positive confirmation that the coordinator can parse the binary header.
// Any unknown — kill-switch off, no ClusterService, empty parent task, coordinator missing from
// cluster state — falls back to JSON, since the cost of an unwarranted JSON emission is small and
// bounded, while the cost of an unwarranted binary emission to an old coordinator is a hung search.
private boolean canCoordinatorReadBinaryHeader(SearchShardTask task) {
if (isBinaryResourceUsageHeaderEnabled() == false) {
return false;
}
if (clusterService == null) {
return false;
}
String coordinatorNodeId = task.getParentTaskId().getNodeId();
if (coordinatorNodeId.isEmpty()) {
return false;
}
DiscoveryNode coordinator = clusterService.state().nodes().get(coordinatorNodeId);
if (coordinator == null) {
return false;
}
return coordinator.getVersion().onOrAfter(BINARY_RESOURCE_USAGE_HEADER_VERSION);
}

/**
* Remove the current task level resource usages.
*/
Expand All @@ -336,29 +401,46 @@ public void removeTaskResourceUsage() {
}

/**
* Get the task resource usages from {@link ThreadContext}
* Get the task resource usages from {@link ThreadContext}.
* <p>
* Tries the new Base64 binary format first; on failure falls back to the legacy JSON form so
* that resource usage from older data nodes is preserved during a rolling upgrade.
*
* @return {@link TaskResourceInfo}
* @return {@link TaskResourceInfo} or null if the header is absent or cannot be deserialized
*/
public TaskResourceInfo getTaskResourceUsageFromThreadContext() {
List<String> taskResourceUsages = threadPool.getThreadContext().getResponseHeaders().get(TASK_RESOURCE_USAGE);
if (taskResourceUsages != null && taskResourceUsages.size() > 0) {
String usage = taskResourceUsages.get(0);
if (taskResourceUsages == null || taskResourceUsages.isEmpty()) {
return null;
}
String usage = taskResourceUsages.get(0);
if (usage == null || usage.isEmpty()) {
return null;
}
try {
return WriteableBase64.decode(usage, TaskResourceInfo::readFromStream);
} catch (Exception binaryFailure) {
try {
if (usage != null && !usage.isEmpty()) {
XContentParser parser = XContentHelper.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
new BytesArray(usage),
MediaTypeRegistry.JSON
);
return TaskResourceInfo.PARSER.apply(parser, null);
}
} catch (IOException e) {
logger.debug("fail to parse phase resource usages: ", e);
return deserializeFromJson(usage);
} catch (Exception jsonFailure) {
logger.debug("failed to parse task resource usage header (binary and JSON), skipping: ", jsonFailure);
return null;
}
}
return null;
}

// Legacy JSON parser for headers emitted by pre-V_3_8_0 data nodes during rolling upgrade.
static TaskResourceInfo deserializeFromJson(String headerValue) throws IOException {
try (
XContentParser parser = XContentHelper.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
new BytesArray(headerValue),
MediaTypeRegistry.JSON
)
) {
return TaskResourceInfo.PARSER.apply(parser, null);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.common.io.stream;

import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.test.OpenSearchTestCase;

import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

public class WriteableBase64Tests extends OpenSearchTestCase {

/** A minimal {@link Writeable} used to exercise the codec independently of any production type. */
private static class Sample implements Writeable {
private final String name;
private final long value;

Sample(String name, long value) {
this.name = name;
this.value = value;
}

Sample(StreamInput in) throws IOException {
this.name = in.readString();
this.value = in.readLong();
}

@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeLong(value);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Sample sample = (Sample) o;
return value == sample.value && Objects.equals(name, sample.name);
}

@Override
public int hashCode() {
return Objects.hash(name, value);
}
}

public void testRoundTrip() throws IOException {
Sample original = new Sample(randomAlphaOfLength(12), randomLong());

String encoded = WriteableBase64.encode(original);
Sample decoded = WriteableBase64.decode(encoded, Sample::new);

assertEquals(original, decoded);
}

public void testEncodeProducesValidBase64() throws IOException {
Sample original = new Sample("action", 42L);

String encoded = WriteableBase64.encode(original);

// Must decode as standard Base64 without throwing; the resulting bytes reconstruct the object.
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
try (StreamInput in = StreamInput.wrap(decodedBytes)) {
assertEquals(original, new Sample(in));
}
}

public void testEmptyStringThrows() {
// An empty payload has no bytes for the reader to consume.
expectThrows(Exception.class, () -> WriteableBase64.decode("", Sample::new));
}

public void testInvalidBase64Throws() {
expectThrows(IllegalArgumentException.class, () -> WriteableBase64.decode("not-valid-base64!!!", Sample::new));
}
}
Loading
Loading