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

[ISSUE#9097] Add new command to check async task status in broker. #9162

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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,147 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.apache.rocketmq.broker;

import com.alibaba.fastjson.JSON;
import com.github.benmanes.caffeine.cache.RemovalCause;
import java.util.concurrent.CompletableFuture;
import org.apache.rocketmq.common.AsyncTask;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.TaskStatus;

public class AdminAsyncTaskManager {
Copy link
Contributor

Choose a reason for hiding this comment

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

if using map to manage task, maybe need a thread to clean up the expired task regularly. Using Caffeine LoadingCache may be better

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done


// taskId -> AsyncTask
private final Cache<String, AsyncTask> asyncTaskCache;

// taskName -> taskId
private final ConcurrentHashMap<String, List<String>> taskNameToIdsMap;

private final BrokerConfig brokerConfig;

private final int taskCacheExpireTimeMinutes;

private final int maxTaskCacheSize;

public AdminAsyncTaskManager(BrokerConfig brokerConfig) {
this.brokerConfig = brokerConfig;
this.taskCacheExpireTimeMinutes = brokerConfig.getTaskCacheExpireTimeMinutes();
this.maxTaskCacheSize = brokerConfig.getMaxTaskCacheSize();
this.taskNameToIdsMap = new ConcurrentHashMap<>();
this.asyncTaskCache = Caffeine.newBuilder()
.expireAfterWrite(taskCacheExpireTimeMinutes, TimeUnit.MINUTES)
.maximumSize(maxTaskCacheSize)
.removalListener((String taskId, AsyncTask task, RemovalCause cause) -> {
if (task != null) {
taskNameToIdsMap.computeIfPresent(task.getTaskName(), (k, list) -> {
list.remove(taskId);
return list.isEmpty() ? null : list;
});
}
})
.build();
}

/**
* Creates a new asynchronous task with a unique taskId.
*
* @param taskName The name of the task.
* @param future The CompletableFuture representing the asynchronous task.
* @return The generated taskId.
*/
public String createTask(String taskName, CompletableFuture<?> future) {
String taskId = UUID.randomUUID().toString();
AsyncTask task = new AsyncTask(taskName, taskId, future);

asyncTaskCache.put(taskId, task);
taskNameToIdsMap.computeIfAbsent(taskName, k -> Collections.synchronizedList(new ArrayList<>())).add(taskId);

future.whenComplete((result, throwable) -> {
if (throwable != null) {
task.setStatus(TaskStatus.ERROR.getValue());
task.setResult(throwable.getMessage());
} else {
task.setStatus(TaskStatus.SUCCESS.getValue());
task.setResult(JSON.toJSONString(result));
}
});

return taskId;
}

/**
* Get all taskIds associated with a given task name.
*
* @param taskName The name of the task.
* @return List of taskIds for the given task name.
*/
public List<String> getTaskIdsByName(String taskName) {
return taskNameToIdsMap.getOrDefault(taskName, Collections.emptyList());
}

/**
* Get the status of a specific task.
*
* @param taskId The unique identifier of the task.
* @return The AsyncTask object, or null if not found.
*/
public AsyncTask getTaskStatus(String taskId) {
return asyncTaskCache.getIfPresent(taskId);
}

/**
* Update the status and result of a specific task.
*
* @param taskId The unique identifier of the task.
* @param status The new status of the task.
* @param result The result of the task.
*/
public void updateTaskStatus(String taskId, int status, String result) {
AsyncTask task = asyncTaskCache.getIfPresent(taskId);
if (task != null) {
task.setStatus(status);
task.setResult(result);
asyncTaskCache.put(taskId, task);
}
}

/**
* Remove a specific task from the cache and mappings.
*
* @param taskId The unique identifier of the task.
*/
public void removeTask(String taskId) {
AsyncTask task = asyncTaskCache.getIfPresent(taskId);
if (task != null) {
asyncTaskCache.invalidate(taskId);
taskNameToIdsMap.computeIfPresent(task.getTaskName(), (k, v) -> {
v.remove(taskId);
return v.isEmpty() ? null : v;
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
Expand All @@ -43,6 +45,7 @@
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.acl.AccessValidator;
Expand All @@ -56,6 +59,7 @@
import org.apache.rocketmq.auth.authorization.exception.AuthorizationException;
import org.apache.rocketmq.auth.authorization.model.Acl;
import org.apache.rocketmq.auth.authorization.model.Resource;
import org.apache.rocketmq.broker.AdminAsyncTaskManager;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.broker.auth.converter.AclConverter;
import org.apache.rocketmq.broker.auth.converter.UserConverter;
Expand All @@ -72,6 +76,7 @@
import org.apache.rocketmq.broker.plugin.BrokerAttachedPlugin;
import org.apache.rocketmq.broker.subscription.SubscriptionGroupManager;
import org.apache.rocketmq.broker.transaction.queue.TransactionalMessageUtil;
import org.apache.rocketmq.common.AsyncTask;
import org.apache.rocketmq.common.BoundaryType;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.CheckRocksdbCqWriteResult;
Expand Down Expand Up @@ -149,6 +154,8 @@
import org.apache.rocketmq.remoting.protocol.body.TopicList;
import org.apache.rocketmq.remoting.protocol.body.UnlockBatchRequestBody;
import org.apache.rocketmq.remoting.protocol.body.UserInfo;
import org.apache.rocketmq.remoting.protocol.header.CheckAsyncTaskStatusRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CheckAsyncTaskStatusResponseHeader;
import org.apache.rocketmq.remoting.protocol.header.CheckRocksdbCqWriteProgressRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CloneGroupOffsetRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.ConsumeMessageDirectlyResultRequestHeader;
Expand Down Expand Up @@ -245,9 +252,11 @@ public class AdminBrokerProcessor implements NettyRequestProcessor {
protected final BrokerController brokerController;
protected Set<String> configBlackList = new HashSet<>();
private final ExecutorService asyncExecuteWorker = new ThreadPoolExecutor(0, 4, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
private final AdminAsyncTaskManager asyncTaskManager;

public AdminBrokerProcessor(final BrokerController brokerController) {
this.brokerController = brokerController;
this.asyncTaskManager = initAsyncTaskManager(brokerController.getBrokerConfig());
initConfigBlackList();
}

Expand All @@ -259,6 +268,13 @@ private void initConfigBlackList() {
configBlackList.addAll(Arrays.asList(configArray));
}

private AdminAsyncTaskManager initAsyncTaskManager(BrokerConfig brokerConfig) {
if (brokerConfig.isEnableAsyncTaskCheck()) {
return new AdminAsyncTaskManager(brokerConfig);
}
return null;
}

@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
Expand Down Expand Up @@ -415,6 +431,8 @@ public RemotingCommand processRequest(ChannelHandlerContext ctx,
return this.listAcl(ctx, request);
case RequestCode.POP_ROLLBACK:
return this.transferPopToFsStore(ctx, request);
case RequestCode.CHECK_ASYNC_TASK_STATUS:
return this.checkAsyncTaskStatus(ctx, request);
default:
return getUnknownCmdResponse(ctx, request);
}
Expand Down Expand Up @@ -487,21 +505,37 @@ private RemotingCommand updateAndGetGroupForbidden(ChannelHandlerContext ctx, Re
private RemotingCommand checkRocksdbCqWriteProgress(ChannelHandlerContext ctx, RemotingCommand request) {
CheckRocksdbCqWriteResult result = new CheckRocksdbCqWriteResult();
result.setCheckStatus(CheckRocksdbCqWriteResult.CheckStatus.CHECK_IN_PROGRESS.getValue());
Runnable runnable = () -> {

CompletableFuture<CheckRocksdbCqWriteResult> future = CompletableFuture.supplyAsync(() -> {
try {
CheckRocksdbCqWriteResult checkResult = doCheckRocksdbCqWriteProgress(ctx, request);
LOGGER.info("checkRocksdbCqWriteProgress result: {}", JSON.toJSONString(checkResult));
return checkResult;
} catch (Exception e) {
LOGGER.error("checkRocksdbCqWriteProgress error", e);
throw new CompletionException(e);
Copy link
Contributor

Choose a reason for hiding this comment

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

log

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

}
};
asyncExecuteWorker.submit(runnable);
}, asyncExecuteWorker);

if (brokerController.getBrokerConfig().isEnableAsyncTaskCheck()) {
String taskId = registerAsyncTask("checkRocksdbCqWriteProgress", future);
result.setTaskId(taskId);
}

RemotingCommand response = RemotingCommand.createResponseCommand(null);
response.setCode(ResponseCode.SUCCESS);
response.setBody(JSON.toJSONBytes(result));
return response;
}

private String registerAsyncTask(String taskName, CompletableFuture<?> future) {
if (asyncTaskManager == null) {
LOGGER.warn("asyncTaskManager not initialized, task registration skipped (enableAsyncTaskCheck config disabled). taskName={}", taskName);
return null;
}
return asyncTaskManager.createTask(taskName, future);
}

private RemotingCommand exportRocksDBConfigToJson(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
ExportRocksDBConfigToJsonRequestHeader requestHeader = request.decodeCommandCustomHeader(ExportRocksDBConfigToJsonRequestHeader.class);
Expand Down Expand Up @@ -3597,4 +3631,51 @@ private RemotingCommand transferPopToFsStore(ChannelHandlerContext ctx, Remoting
}
return response;
}

private RemotingCommand checkAsyncTaskStatus(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
if (!brokerController.getBrokerConfig().isEnableAsyncTaskCheck()) {
throw new RemotingCommandException("async task check is not enabled");
}

final CheckAsyncTaskStatusRequestHeader requestHeader = request.decodeCommandCustomHeader(CheckAsyncTaskStatusRequestHeader.class);
String taskId = requestHeader.getTaskId();
String taskName = requestHeader.getTaskName();

RemotingCommand response = RemotingCommand.createResponseCommand(CheckAsyncTaskStatusResponseHeader.class);
// If the taskId is not empty, query the async task with the specified taskId.
if (StringUtils.isNotBlank(taskId)) {
AsyncTask asyncTask = asyncTaskManager.getTaskStatus(requestHeader.getTaskId());
if (asyncTask == null) {
throw new RemotingCommandException("taskId: " + requestHeader.getTaskId() + " not found");
}
response.setCode(ResponseCode.SUCCESS);
response.setBody(JSON.toJSONBytes(asyncTask));
return response;
}

List<String> taskIds = asyncTaskManager.getTaskIdsByName(taskName);
if (CollectionUtils.isEmpty(taskIds)) {
throw new RemotingCommandException("taskName: " + requestHeader.getTaskName() + " not found");
}

try {
int maxResults = Math.min(requestHeader.getMaxLimit(), 200);
Integer filterStatus = requestHeader.getTaskStatus();

List<AsyncTask> asyncTasks = taskIds.stream()
.map(asyncTaskManager::getTaskStatus)
.filter(Objects::nonNull)
.filter(task -> filterStatus == null || task.getStatus() == filterStatus)
.sorted(Comparator.comparing(AsyncTask::getCreateTime).reversed())
.limit(maxResults)
.collect(Collectors.toList());

response.setCode(ResponseCode.SUCCESS);
response.setBody(JSON.toJSONBytes(asyncTasks));
return response;
} catch (Exception e) {
LOGGER.error("checkAsyncTaskStatus error", e);
return RemotingCommand.createResponseCommand(ResponseCode.SYSTEM_ERROR, e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.apache.rocketmq.broker.topic.TopicConfigManager;
import org.apache.rocketmq.common.BoundaryType;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.CheckRocksdbCqWriteResult;
import org.apache.rocketmq.common.KeyBuilder;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.MixAll;
Expand Down Expand Up @@ -73,6 +74,8 @@
import org.apache.rocketmq.remoting.protocol.body.QueryCorrectionOffsetBody;
import org.apache.rocketmq.remoting.protocol.body.UnlockBatchRequestBody;
import org.apache.rocketmq.remoting.protocol.body.UserInfo;
import org.apache.rocketmq.remoting.protocol.header.CheckAsyncTaskStatusRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CheckRocksdbCqWriteProgressRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CreateAclRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CreateTopicRequestHeader;
import org.apache.rocketmq.remoting.protocol.header.CreateUserRequestHeader;
Expand Down Expand Up @@ -230,7 +233,8 @@ public void init() throws Exception {
field.set(brokerController, broker2Client);

//doReturn(sendMessageProcessor).when(brokerController).getSendMessageProcessor();

BrokerConfig config = brokerController.getBrokerConfig();
config.setEnableAsyncTaskCheck(true);
adminBrokerProcessor = new AdminBrokerProcessor(brokerController);

systemTopicSet = Sets.newHashSet(
Expand Down Expand Up @@ -1328,6 +1332,44 @@ public void testResetMasterFlushOffset() throws RemotingCommandException {
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
}

@Test
public void testCheckAsyncTaskStatusByTaskId() throws RemotingCommandException {
CheckRocksdbCqWriteProgressRequestHeader requestHeader = new CheckRocksdbCqWriteProgressRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_ROCKSDB_CQ_WRITE_PROGRESS, requestHeader);

RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request);
CheckRocksdbCqWriteResult results = RemotingSerializable.decode(response.getBody(), CheckRocksdbCqWriteResult.class);
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);

CheckAsyncTaskStatusRequestHeader requestHeader1 = new CheckAsyncTaskStatusRequestHeader();
requestHeader1.setTaskId(results.getTaskId());
RemotingCommand request1 = RemotingCommand.createRequestCommand(RequestCode.CHECK_ASYNC_TASK_STATUS, requestHeader1);
HashMap<String, String> extFields = new HashMap<>();
extFields.put("taskId",results.getTaskId());
request1.setExtFields(extFields);
RemotingCommand response1 = adminBrokerProcessor.processRequest(handlerContext, request1);
assertThat(response1.getCode()).isEqualTo(ResponseCode.SUCCESS);
}

@Test
public void testCheckAsyncTaskStatusByTaskName() throws RemotingCommandException {
CheckRocksdbCqWriteProgressRequestHeader requestHeader = new CheckRocksdbCqWriteProgressRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_ROCKSDB_CQ_WRITE_PROGRESS, requestHeader);

RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request);
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);

String taskName = "checkRocksdbCqWriteProgress";
CheckAsyncTaskStatusRequestHeader requestHeader1 = new CheckAsyncTaskStatusRequestHeader();
requestHeader1.setTaskName(taskName);
RemotingCommand request1 = RemotingCommand.createRequestCommand(RequestCode.CHECK_ASYNC_TASK_STATUS, requestHeader1);
HashMap<String, String> extFields = new HashMap<>();
extFields.put("taskName",taskName);
request1.setExtFields(extFields);
RemotingCommand response1 = adminBrokerProcessor.processRequest(handlerContext, request1);
assertThat(response1.getCode()).isEqualTo(ResponseCode.SUCCESS);
}

private ResetOffsetRequestHeader createRequestHeader(String topic,String group,long timestamp,boolean force,long offset,int queueId) {
ResetOffsetRequestHeader requestHeader = new ResetOffsetRequestHeader();
requestHeader.setTopic(topic);
Expand Down
Loading
Loading