Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search Task Resource Tracking PoC #1643

Closed
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,89 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.elasticsearch.search.stats;


import org.opensearch.action.ActionFuture;
import org.opensearch.action.admin.indices.stats.IndicesStatsResponse;
import org.opensearch.action.admin.indices.stats.ShardStats;
import org.opensearch.action.index.IndexRequestBuilder;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.cluster.routing.ShardRouting;
import org.opensearch.common.settings.Settings;
import org.opensearch.test.OpenSearchIntegTestCase;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.opensearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.opensearch.index.query.QueryBuilders.matchAllQuery;
import static org.opensearch.search.aggregations.AggregationBuilders.count;
import static org.opensearch.test.OpenSearchIntegTestCase.*;


@ClusterScope(scope = Scope.SUITE, supportsDedicatedMasters = false, numDataNodes = 3, numClientNodes = 1)
public class TaskResourceTrackerIT extends OpenSearchIntegTestCase {

private void addDocuments(String index, int start, int end) throws Exception {
List<IndexRequestBuilder> builders = new ArrayList<>();
for (int i = start; i < end; i++) {
builders.add(client().prepareIndex(index, "type", "" + i + 1).setSource(jsonBuilder()
.startObject()
.field("value", i + 1)
.field("tag", "tag" + i)
.endObject()));
}

indexRandom(true, builders);
ensureSearchable();
}

public void testAggregation() throws Exception {
String index = "idx";
createIndex(index, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 3).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).build());
addDocuments(index, 0, 50);

ActionFuture<SearchResponse> searchResponseActionFuture = client().prepareSearch(index)
.setQuery(matchAllQuery())
.addAggregation(count("count").field("value"))
.execute();

List<String> nodeIds = getNodeNames(index);

// Thread.sleep(6000);

// NodesStatsResponse nodesStats = client().admin().cluster().prepareNodesStats().addMetric("thread_pool/search").get();

searchResponseActionFuture.get();
}

private List<String> getNodeNames(String indexName) {
IndicesStatsResponse response = client().admin().indices().prepareStats(indexName).get();
return Stream.of(response.getShards())
.map(ShardStats::getShardRouting)
.filter(ShardRouting::primary)
.map(ShardRouting::currentNodeId)
.collect(Collectors.toList());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@

package org.opensearch.action.search;

import com.sun.management.ThreadMXBean;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.util.SetOnce;
import org.opensearch.tasks.TaskResourceTracker;
import org.opensearch.ExceptionsHelper;
import org.opensearch.OpenSearchException;
import org.opensearch.Version;
Expand All @@ -56,8 +58,10 @@
import org.opensearch.search.internal.InternalSearchResponse;
import org.opensearch.search.internal.SearchContext;
import org.opensearch.search.internal.ShardSearchRequest;
import org.opensearch.tasks.TaskResourceTracker;
import org.opensearch.transport.Transport;

import java.lang.management.ManagementFactory;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -283,6 +287,10 @@ public void innerOnResponse(Result result) {
} finally {
executeNext(pendingExecutions, thread);
}
ThreadMXBean threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is expensive. Move this to a static final variable

long bytes = threadMXBean.getThreadAllocatedBytes(Thread.currentThread().getId());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, it is worth checking if thread allocation tracking is enabled & supported, for not doing unnecessary work: ThreadMXBean::isThreadAllocatedMemorySupported() and ThreadMXBean::isThreadAllocatedMemoryEnabled()


TaskResourceTracker.getInstance().transfer(task.getId(), result, bytes);
Comment on lines +292 to +293
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be too hard to maintain the code base with this construct. Lets simplify

}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,16 @@ public static OpenSearchThreadPoolExecutor newAutoQueueFixed(
ConcurrentCollections.<Runnable>newBlockingQueue(),
initialQueueCapacity
);
Function<Runnable, WrappedRunnable> runnableWrapper;
if (name.endsWith("search")) {
runnableWrapper = (r) -> {
ResourceRunnable rr = new ResourceRunnable(contextHolder, r, name);
return new TimedRunnable(rr);
};
} else {
runnableWrapper = TimedRunnable::new;
}

return new QueueResizingOpenSearchThreadPoolExecutor(
name,
size,
Expand All @@ -210,7 +220,7 @@ public static OpenSearchThreadPoolExecutor newAutoQueueFixed(
queue,
minQueueSize,
maxQueueSize,
TimedRunnable::new,
runnableWrapper,
frameSize,
targetedResponseTime,
threadFactory,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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.util.concurrent;

import java.lang.management.ManagementFactory;
import java.util.Objects;

import com.sun.management.ThreadMXBean;
import org.opensearch.ExceptionsHelper;
import org.opensearch.tasks.TaskResourceTracker;

public class ResourceRunnable extends AbstractRunnable implements WrappedRunnable {
Copy link
Collaborator

@Bukhtawar Bukhtawar Dec 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets add java docs to explain how threads running cost is computed and associated with the corresponding task


private Runnable original;
private ThreadContext threadContext;
ThreadMXBean threadMXBean;
private String taskId;
private String threadpoolName;

public ResourceRunnable(ThreadContext threadContext, final Runnable original, String name) {
this.original = original;
this.threadContext = threadContext;
this.threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean();
this.threadpoolName = name;
}

@Override
public void onFailure(Exception e) {
if (original instanceof AbstractRunnable) {
((AbstractRunnable) original).onRejection(e);
} else {
ExceptionsHelper.reThrowIfNotNull(e);
}
}

@Override
protected void doRun() throws Exception {
if (Objects.nonNull(threadContext.getTransient("TASK_ID"))) {
String taskId = threadContext.getTransient("TASK_ID");
long threadId = Thread.currentThread().getId();
TaskResourceTracker.getInstance().registerWorkerForTask(Long.parseLong(taskId), threadId,
threadMXBean.getCurrentThreadCpuTime(),
threadMXBean.getThreadAllocatedBytes(threadId), threadpoolName);
}
try {
original.run();
} finally {
if (Objects.nonNull(threadContext.getTransient("TASK_ID"))) {
String taskId = threadContext.getTransient("TASK_ID");
long threadId = Thread.currentThread().getId();
TaskResourceTracker.getInstance().unregisterWorkerForTask(Long.parseLong(taskId), threadId,
threadMXBean.getCurrentThreadCpuTime(), threadMXBean.getThreadAllocatedBytes(threadId));
}
}

}

@Override
public Runnable unwrap() {
return original;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,12 @@ public StoredContext stashContext() {
.put(Task.X_OPAQUE_ID, context.requestHeaders.get(Task.X_OPAQUE_ID))
.immutableMap()
);
threadLocal.set(threadContextStruct);
} else {
threadLocal.set(DEFAULT_CONTEXT);
}
if (context.transientHeaders.containsKey("TASK_ID")) {
DEFAULT_CONTEXT.putTransient("TASK_ID", context.transientHeaders.get("TASK_ID"));
}
threadLocal.set(DEFAULT_CONTEXT);

return () -> {
// If the node and thus the threadLocal get closed while this task
// is still executing, we don't want this runnable to fail with an
Expand Down
2 changes: 2 additions & 0 deletions server/src/main/java/org/opensearch/node/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.SetOnce;
import org.opensearch.tasks.TaskResourceTracker;
import org.opensearch.index.IndexingPressureService;
import org.opensearch.watcher.ResourceWatcherService;
import org.opensearch.Assertions;
Expand Down Expand Up @@ -431,6 +432,7 @@ protected Node(
resourcesToClose.add(() -> ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS));
final ResourceWatcherService resourceWatcherService = new ResourceWatcherService(settings, threadPool);
resourcesToClose.add(resourceWatcherService);
resourceWatcherService.add(TaskResourceTracker.getInstance(), ResourceWatcherService.Frequency.HIGH);
Copy link
Collaborator

@Bukhtawar Bukhtawar Dec 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to watch per 5s, seems wasteful. Instead it should be tied to the overall usage subject to high utilization beyond a threshold or individual task level resource utilization or on-demand

// adds the context to the DeprecationLogger so that it does not need to be injected everywhere
HeaderWarning.setThreadContext(threadPool.getThreadContext());
resourcesToClose.add(() -> HeaderWarning.removeThreadContext(threadPool.getThreadContext()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ protected Table getTableWithHeader(final RestRequest request) {
table.addCell("max", "alias:mx;default:false;text-align:right;desc:maximum number of threads in a scaling thread pool");
table.addCell("size", "alias:sz;default:false;text-align:right;desc:number of threads in a fixed thread pool");
table.addCell("keep_alive", "alias:ka;default:false;text-align:right;desc:thread keep alive time");
table.addCell("bytes", "alias:by;default:true;text-align:right;desc:Bytes consumed");
table.addCell("resposne_overhead", "alias:ro;default:true;text-align:right;desc:Response overhead");
table.endHeaders();
return table;
}
Expand Down Expand Up @@ -260,6 +262,8 @@ private Table buildTable(RestRequest req, ClusterStateResponse state, NodesInfoR
table.addCell(max);
table.addCell(size);
table.addCell(keepAlive);
table.addCell(poolStats == null ? null : poolStats.getBytes());
table.addCell(poolStats == null ? null : poolStats.getRO());

table.endRow();
}
Expand Down
60 changes: 60 additions & 0 deletions server/src/main/java/org/opensearch/tasks/TaskInfoKey.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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.tasks;

import org.opensearch.index.shard.ShardId;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TaskInfoKey {

private final long taskId;
private final List<String> indices;
private final ShardId shardId;
private final String action;

public TaskInfoKey(long taskId) {
this(taskId, new ArrayList<>(), null, null);
}

public TaskInfoKey(long taskId, List<String> indices, ShardId shardId, String action) {
this.taskId = taskId;
this.indices = indices;
this.shardId = shardId;
this.action = action;
}
Comment on lines +28 to +33
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Task is so far not bound to a ShardId, this should be more generic


public long getTaskId() {
return taskId;
}

public List<String> getIndices() {
return indices;
}

public ShardId getShardId() {
return shardId;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskInfoKey that = (TaskInfoKey) o;
return Objects.equals(taskId, that.taskId);
}

@Override
public int hashCode() {
return Objects.hash(taskId);
}

}
18 changes: 18 additions & 0 deletions server/src/main/java/org/opensearch/tasks/TaskManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.lucene.util.SetOnce;
import org.opensearch.tasks.TaskResourceTracker;
import org.opensearch.Assertions;
import org.opensearch.ExceptionsHelper;
import org.opensearch.OpenSearchException;
import org.opensearch.OpenSearchTimeoutException;
import org.opensearch.action.ActionListener;
import org.opensearch.action.ActionResponse;
import org.opensearch.action.IndicesRequest;
import org.opensearch.cluster.ClusterChangedEvent;
import org.opensearch.cluster.ClusterStateApplier;
import org.opensearch.cluster.node.DiscoveryNode;
Expand All @@ -62,6 +64,7 @@

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -150,6 +153,20 @@ public Task register(String type, String action, TaskAwareRequest request) {
logger.trace("register {} [{}] [{}] [{}]", task.getId(), type, action, task.getDescription());
}

// just register read operations
if (action.startsWith("indices:data/read")) {
Copy link
Collaborator

@reta reta Dec 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to enrich action with something like isResourceTrackingEnabled() and use it as an indicator of the need to track resources. Also, the tracking key (in this case, indices, but is action specific) has to be provided by the action as as well, fe as getResourceTrackingKey method.

if (threadContext.getTransient("TASK_ID") == null) {
threadContext.putTransient("TASK_ID", String.valueOf(task.getId()));

List<String> indices = new ArrayList<>();
if (request instanceof IndicesRequest) {
indices = Arrays.asList(((IndicesRequest) request).indices());
}
// TODO Add shard id handling
TaskResourceTracker.getInstance().registerTaskForTracking(task.getId(), indices, null, action);
}
}

Comment on lines +156 to +169
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why can't this be modelled as a TaskListener

if (task instanceof CancellableTask) {
registerCancellableTask(task);
} else {
Expand Down Expand Up @@ -202,6 +219,7 @@ public void cancel(CancellableTask task, String reason, Runnable listener) {
*/
public Task unregister(Task task) {
logger.trace("unregister task for id: {}", task.getId());
TaskResourceTracker.getInstance().unregisterTaskForTracking(task.getId());
if (task instanceof CancellableTask) {
CancellableTaskHolder holder = cancellableTasks.remove(task.getId());
if (holder != null) {
Expand Down
Loading