-
Notifications
You must be signed in to change notification settings - Fork 11.8k
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
KiteSoar
wants to merge
5
commits into
apache:develop
Choose a base branch
from
KiteSoar:develop-#9097
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
bf4a370
[ISSUE #9097]Add new command to check async task status in broker.
KiteSoar 2637c95
[ISSUE#9097]Optimize adminAsyncTaskManager.
KiteSoar 97bcdeb
[ISSUE#9097]Move params to broker config.
KiteSoar 690acb0
[ISSUE#9097] Add async task manager switch.
KiteSoar ce88393
[ISSUE#9097] Add UT.
KiteSoar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
147 changes: 147 additions & 0 deletions
147
broker/src/main/java/org/apache/rocketmq/broker/AdminAsyncTaskManager.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
|
||
// 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; | ||
}); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
@@ -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; | ||
|
@@ -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; | ||
|
@@ -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; | ||
|
@@ -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; | ||
|
@@ -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(); | ||
} | ||
|
||
|
@@ -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 { | ||
|
@@ -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); | ||
} | ||
|
@@ -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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. log There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
|
@@ -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()); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done