feat(任务中心): 任务列表批量删除停止

This commit is contained in:
WangXu10 2024-10-17 15:57:27 +08:00 committed by Craftsman
parent 9f3aecc67a
commit a67d17d494
11 changed files with 302 additions and 43 deletions

View File

@ -115,7 +115,8 @@ public class ProjectTaskHubControllerTests extends BaseTest {
@Test @Test
@Order(6) @Order(6)
public void projectTaskStop() throws Exception { public void projectTaskStop() throws Exception {
MvcResult mvcResult = this.requestGetWithOkAndReturn(PROJECT_TASK_STOP + "1"); this.requestGet(PROJECT_TASK_STOP + "pro_1");
MvcResult mvcResult = this.requestGetWithOkAndReturn(PROJECT_TASK_STOP + "pro_2");
// 获取返回值 // 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);

View File

@ -5,4 +5,11 @@ VALUES
('pro_3', 3, '测试任务3', 'SUCCESS', 11, 'SUCCESS', 'FUNCTIONAL', 'API', '100001100001', '11234', 1727676089639, 'wx', 1727676089639, 1727676089639); ('pro_3', 3, '测试任务3', 'SUCCESS', 11, 'SUCCESS', 'FUNCTIONAL', 'API', '100001100001', '11234', 1727676089639, 'wx', 1727676089639, 1727676089639);
INSERT INTO `exec_task_item`(`id`, `task_id`, `resource_id`, `resource_name`, `task_origin`, `status`, `result`, `resource_pool_id`, `resource_pool_node`, `resource_type`, `project_id`, `organization_id`, `thread_id`, `start_time`, `end_time`, `executor`) INSERT INTO `exec_task_item`(`id`, `task_id`, `resource_id`, `resource_name`, `task_origin`, `status`, `result`, `resource_pool_id`, `resource_pool_node`, `resource_type`, `project_id`, `organization_id`, `thread_id`, `start_time`, `end_time`, `executor`)
VALUES ('pro_1', 'pro_1', '1', '1', '1', 'SUCCESS', 'SUCCESS', '1', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin'); VALUES
('pro_1', 'pro_1', '1', '1', '1', 'SUCCESS', 'SUCCESS', '1', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin'),
('pro_2', 'pro_2', '1', '1', '1', 'SUCCESS', 'SUCCESS', '2', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin');
INSERT INTO `test_resource_pool` (`id`, `name`, `type`, `description`, `enable`, `create_time`, `update_time`, `create_user`, `server_url`, `all_org`, `deleted`)
VALUES
('1', 'LOCAL', 'Node', '测试资源池', b'1', 1705894549000, 1705894549000, 'admin', NULL, b'1', b'0'),
('2', 'LOCAL', 'Kubernetes', 'Kubernetes测试资源池', b'1', 1705894549000, 1705894549000, 'admin', NULL, b'1', b'0');

View File

@ -2,7 +2,7 @@ package io.metersphere.system.controller;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.system.dto.sdk.BasePageRequest; import io.metersphere.system.dto.sdk.BasePageRequest;
import io.metersphere.system.dto.taskcenter.request.TaskCenterBatchRequest; import io.metersphere.system.dto.table.TableBatchProcessDTO;
import io.metersphere.system.dto.taskhub.*; import io.metersphere.system.dto.taskhub.*;
import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest; import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest;
import io.metersphere.system.dto.taskhub.response.TaskStatisticsResponse; import io.metersphere.system.dto.taskhub.response.TaskStatisticsResponse;
@ -10,7 +10,6 @@ import io.metersphere.system.log.annotation.Log;
import io.metersphere.system.log.constants.OperationLogType; import io.metersphere.system.log.constants.OperationLogType;
import io.metersphere.system.service.BaseTaskHubLogService; import io.metersphere.system.service.BaseTaskHubLogService;
import io.metersphere.system.service.BaseTaskHubService; import io.metersphere.system.service.BaseTaskHubService;
import io.metersphere.system.service.SystemOrganizationLogService;
import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.Pager;
import io.metersphere.system.utils.SessionUtils; import io.metersphere.system.utils.SessionUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@ -83,13 +82,22 @@ public class SystemTaskHubController {
@GetMapping("/exec-task/stop/{id}") @GetMapping("/exec-task/stop/{id}")
@Operation(summary = "系统-任务中心-用例执行任务-停止任务") @Operation(summary = "系统-任务中心-用例执行任务-停止任务")
@Log(type = OperationLogType.UPDATE, expression = "#msClass.systemStopLog(#id)", msClass = BaseTaskHubLogService.class) @Log(type = OperationLogType.STOP, expression = "#msClass.systemStopLog(#id)", msClass = BaseTaskHubLogService.class)
@RequiresPermissions(PermissionConstants.SYSTEM_CASE_TASK_CENTER_EXEC_STOP) @RequiresPermissions(PermissionConstants.SYSTEM_CASE_TASK_CENTER_EXEC_STOP)
public void stopTask(@PathVariable String id) { public void stopTask(@PathVariable String id) {
baseTaskHubService.stopTask(id, SessionUtils.getUserId(), null, null); baseTaskHubService.stopTask(id, SessionUtils.getUserId(), null, null);
} }
@PostMapping("/exec-task/batch-stop")
@Operation(summary = "系统-任务中心-用例执行任务-批量停止任务")
@Log(type = OperationLogType.STOP, expression = "#msClass.systemBatchStopLog(#request)", msClass = BaseTaskHubLogService.class)
@RequiresPermissions(PermissionConstants.SYSTEM_CASE_TASK_CENTER_EXEC_STOP)
public void batchStopTask(@Validated @RequestBody TableBatchProcessDTO request) {
baseTaskHubService.batchStopTask(request, SessionUtils.getUserId(), null, null);
}
@GetMapping("/exec-task/delete/{id}") @GetMapping("/exec-task/delete/{id}")
@Operation(summary = "系统-任务中心-用例执行任务-删除任务") @Operation(summary = "系统-任务中心-用例执行任务-删除任务")
@Log(type = OperationLogType.DELETE, expression = "#msClass.systemDeleteLog(#id)", msClass = BaseTaskHubLogService.class) @Log(type = OperationLogType.DELETE, expression = "#msClass.systemDeleteLog(#id)", msClass = BaseTaskHubLogService.class)

View File

@ -18,4 +18,8 @@ public interface ExtExecTaskItemMapper {
List<ExecTaskItem> selectPoolNodeByIds(@Param("ids") List<String> ids); List<ExecTaskItem> selectPoolNodeByIds(@Param("ids") List<String> ids);
List<ExecTaskItem> selectExecInfoByResourceIds(@Param("resourceIds") List<String> resourceIds); List<ExecTaskItem> selectExecInfoByResourceIds(@Param("resourceIds") List<String> resourceIds);
List<ExecTaskItem> getResourcePoolsByTaskIds(@Param("taskIds") List<String> taskIds);
void batchUpdateTaskItemStatus(@Param("taskIds") List<String> taskIds, @Param("userId") String userId, @Param("organizationId") String organizationId, @Param("projectId") String projectId, @Param("status") String status);
} }

View File

@ -92,4 +92,38 @@
</if> </if>
</sql> </sql>
<select id="getResourcePoolsByTaskIds" resultType="io.metersphere.system.domain.ExecTaskItem">
SELECT
id,
task_id,
resource_pool_node,
resource_pool_id
FROM
exec_task_item
<if test="taskIds != null and taskIds.size() > 0">
WHERE task_id IN
<foreach collection="taskIds" item="taskId" open="(" separator="," close=")">
#{taskId}
</foreach>
</if>
</select>
<update id="batchUpdateTaskItemStatus">
UPDATE exec_task_item
SET `status` = #{status},
executor = #{userId}
WHERE task_id in
<foreach collection="taskIds" item="taskId" open="(" separator="," close=")">
#{taskId}
</foreach>
<if test="projectId != null and projectId != ''">
and project_id = #{projectId}
</if>
<if test="organizationId != null and organizationId != ''">
and organization_id = #{organizationId}
</if>
and `status` = 'RUNNING'
</update>
</mapper> </mapper>

View File

@ -2,6 +2,7 @@ package io.metersphere.system.mapper;
import io.metersphere.system.domain.ExecTask; import io.metersphere.system.domain.ExecTask;
import io.metersphere.system.dto.sdk.BasePageRequest; import io.metersphere.system.dto.sdk.BasePageRequest;
import io.metersphere.system.dto.table.TableBatchProcessDTO;
import io.metersphere.system.dto.taskhub.TaskHubDTO; import io.metersphere.system.dto.taskhub.TaskHubDTO;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@ -13,7 +14,9 @@ import java.util.List;
public interface ExtExecTaskMapper { public interface ExtExecTaskMapper {
List<TaskHubDTO> selectList(@Param("request") BasePageRequest request, @Param("orgId") String orgId, @Param("projectId") String projectId); List<TaskHubDTO> selectList(@Param("request") BasePageRequest request, @Param("orgId") String orgId, @Param("projectId") String projectId);
void updateTaskStatus(@Param("execTask") ExecTask execTask);
void deleteTaskById(@Param("id") String id, @Param("orgId") String orgId, @Param("projectId") String projectId); void deleteTaskById(@Param("id") String id, @Param("orgId") String orgId, @Param("projectId") String projectId);
List<String> getIds(@Param("request") TableBatchProcessDTO request);
void batchUpdateTaskStatus(@Param("ids") List<String> ids, @Param("userId") String userId, @Param("organizationId") String organizationId, @Param("projectId") String projectId, @Param("status") String status);
} }

View File

@ -17,23 +17,15 @@
<if test="projectId != null"> <if test="projectId != null">
and exec_task.project_id = #{projectId} and exec_task.project_id = #{projectId}
</if> </if>
<include refid="queryWhereCondition"/>
</where> </where>
</select> </select>
<sql id="queryWhereCondition">
<include refid="filters">
<property name="filter" value="request.filter"/>
</include>
</sql>
<update id="updateTaskStatus">
UPDATE exec_task
SET `status` = #{execTask.status},
create_user = #{execTask.createUser}
WHERE
id = #{execTask.id}
<if test="execTask.projectId != null and execTask.projectId != ''">
and project_id = #{execTask.projectId}
</if>
<if test="execTask.organizationId != null and execTask.organizationId != ''">
and organization_id = #{execTask.organizationId}
</if>
and `status` = 'RUNNING'
</update>
<delete id="deleteTaskById"> <delete id="deleteTaskById">
DELETE DELETE
@ -47,4 +39,70 @@
</if> </if>
and `status` in ('PENDING', 'STOPPED', 'COMPLETED') and `status` in ('PENDING', 'STOPPED', 'COMPLETED')
</delete> </delete>
<select id="getIds" resultType="java.lang.String">
select id from exec_task
<where>
<include refid="queryWhereConditionByBaseQueryRequest"/>
</where>
</select>
<sql id="queryWhereConditionByBaseQueryRequest">
<if test="request.condition.keyword != null and request.condition.keyword != ''">
and (
exec_task.num like concat('%', #{request.keyword},'%')
or exec_task.task_name like concat('%', #{request.keyword},'%')
)
</if>
<include refid="filters">
<property name="filter" value="request.condition.filter"/>
</include>
</sql>
<sql id="filters">
<if test="${filter} != null and ${filter}.size() > 0">
<foreach collection="${filter}.entrySet()" index="key" item="values">
<if test="values != null and values.size() > 0">
<choose>
<!-- 执行状态 -->
<when test="key=='status'">
and exec_task.status in
<include refid="io.metersphere.system.mapper.BaseMapper.filterInWrapper"/>
</when>
<!-- 执行方式 -->
<when test="key=='triggerMode'">
and exec_task.trigger_mode in
<include refid="io.metersphere.system.mapper.BaseMapper.filterInWrapper"/>
</when>
<!-- 执行结果 -->
<when test="key=='result'">
and exec_task.result in
<include refid="io.metersphere.system.mapper.BaseMapper.filterInWrapper"/>
</when>
</choose>
</if>
</foreach>
</if>
</sql>
<update id="batchUpdateTaskStatus">
UPDATE exec_task
SET `status` = #{status},
create_user = #{userId}
WHERE id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
<if test="projectId != null and projectId != ''">
and project_id = #{projectId}
</if>
<if test="organizationId != null and organizationId != ''">
and organization_id = #{organizationId}
</if>
and `status` = 'RUNNING'
</update>
</mapper> </mapper>

View File

@ -3,16 +3,22 @@ package io.metersphere.system.service;
import io.metersphere.sdk.constants.OperationLogConstants; import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.util.JSON; import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.ExecTask; import io.metersphere.system.domain.ExecTask;
import io.metersphere.system.domain.ExecTaskExample;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.dto.sdk.request.UserRoleUpdateRequest; import io.metersphere.system.dto.sdk.request.UserRoleUpdateRequest;
import io.metersphere.system.dto.table.TableBatchProcessDTO;
import io.metersphere.system.log.constants.OperationLogModule; import io.metersphere.system.log.constants.OperationLogModule;
import io.metersphere.system.log.constants.OperationLogType; import io.metersphere.system.log.constants.OperationLogType;
import io.metersphere.system.log.dto.LogDTO; import io.metersphere.system.log.dto.LogDTO;
import io.metersphere.system.mapper.ExecTaskMapper; import io.metersphere.system.mapper.ExecTaskMapper;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author wx * @author wx
*/ */
@ -21,7 +27,8 @@ import org.springframework.transaction.annotation.Transactional;
public class BaseTaskHubLogService { public class BaseTaskHubLogService {
@Resource @Resource
private ExecTaskMapper execTaskMapper; private ExecTaskMapper execTaskMapper;
@Resource
private BaseTaskHubService baseTaskHubService;
/** /**
* 系统停止任务日志 * 系统停止任务日志
@ -44,6 +51,34 @@ public class BaseTaskHubLogService {
return dto; return dto;
} }
/**
* 系统批量停止任务日志
*
* @param request
* @return
*/
public List<LogDTO> systemBatchStopLog(TableBatchProcessDTO request) {
List<String> ids = baseTaskHubService.getTaskIds(request);
ExecTaskExample example = new ExecTaskExample();
example.createCriteria().andIdIn(ids);
List<ExecTask> execTasks = execTaskMapper.selectByExample(example);
List<LogDTO> logDTOList = new ArrayList<>();
if (CollectionUtils.isNotEmpty(execTasks)) {
execTasks.forEach(item -> {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
item.getId(),
null,
OperationLogType.STOP.name(),
OperationLogModule.SETTING_SYSTEM_TASK_CENTER,
item.getTaskName());
logDTOList.add(dto);
});
}
return logDTOList;
}
/** /**
* 组织停止任务日志 * 组织停止任务日志

View File

@ -2,6 +2,8 @@ package io.metersphere.system.service;
import com.github.pagehelper.Page; import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod; import com.github.pagehelper.page.PageMethod;
import io.metersphere.engine.EngineFactory;
import io.metersphere.engine.MsHttpClient;
import io.metersphere.project.domain.Project; import io.metersphere.project.domain.Project;
import io.metersphere.project.domain.ProjectExample; import io.metersphere.project.domain.ProjectExample;
import io.metersphere.project.domain.ProjectTestResourcePool; import io.metersphere.project.domain.ProjectTestResourcePool;
@ -9,14 +11,19 @@ import io.metersphere.project.domain.ProjectTestResourcePoolExample;
import io.metersphere.project.mapper.ProjectMapper; import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.project.mapper.ProjectTestResourcePoolMapper; import io.metersphere.project.mapper.ProjectTestResourcePoolMapper;
import io.metersphere.sdk.constants.ExecStatus; import io.metersphere.sdk.constants.ExecStatus;
import io.metersphere.sdk.constants.ResourcePoolTypeEnum;
import io.metersphere.sdk.constants.ResultStatus; import io.metersphere.sdk.constants.ResultStatus;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.JSON; import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.LogUtils;
import io.metersphere.sdk.util.SubListUtils; import io.metersphere.sdk.util.SubListUtils;
import io.metersphere.system.domain.*; import io.metersphere.system.domain.*;
import io.metersphere.system.dto.pool.TestResourceDTO; import io.metersphere.system.dto.pool.TestResourceDTO;
import io.metersphere.system.dto.pool.TestResourceNodeDTO; import io.metersphere.system.dto.pool.TestResourceNodeDTO;
import io.metersphere.system.dto.pool.TestResourcePoolReturnDTO;
import io.metersphere.system.dto.sdk.BasePageRequest; import io.metersphere.system.dto.sdk.BasePageRequest;
import io.metersphere.system.dto.sdk.OptionDTO; import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.system.dto.table.TableBatchProcessDTO;
import io.metersphere.system.dto.taskhub.*; import io.metersphere.system.dto.taskhub.*;
import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest; import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest;
import io.metersphere.system.dto.taskhub.response.TaskStatisticsResponse; import io.metersphere.system.dto.taskhub.response.TaskStatisticsResponse;
@ -82,6 +89,8 @@ public class BaseTaskHubService {
private OrganizationMapper organizationMapper; private OrganizationMapper organizationMapper;
@Resource @Resource
private UserMapper userMapper; private UserMapper userMapper;
@Resource
private TestResourcePoolService testResourcePoolService;
/** /**
* 系统-获取执行任务列表 * 系统-获取执行任务列表
@ -282,12 +291,23 @@ public class BaseTaskHubService {
return; return;
} }
List<String> userIds = list.stream().map(TaskHubItemDTO::getExecutor).distinct().toList(); List<String> userIds = list.stream().map(TaskHubItemDTO::getExecutor).distinct().toList();
List<String> resourcePoolIds = list.stream().map(TaskHubItemDTO::getResourcePoolId).distinct().toList();
Map<String, String> userMaps = getUserMaps(userIds); Map<String, String> userMaps = getUserMaps(userIds);
Map<String, String> resourcePoolMaps = getResourcePoolMaps(resourcePoolIds);
list.forEach(item -> { list.forEach(item -> {
item.setUserName(userMaps.getOrDefault(item.getExecutor(), StringUtils.EMPTY)); item.setUserName(userMaps.getOrDefault(item.getExecutor(), StringUtils.EMPTY));
item.setResourcePoolName(resourcePoolMaps.getOrDefault(item.getResourcePoolId(), StringUtils.EMPTY));
}); });
} }
private Map<String, String> getResourcePoolMaps(List<String> resourcePoolIds) {
TestResourcePoolExample poolExample = new TestResourcePoolExample();
poolExample.createCriteria().andIdIn(resourcePoolIds);
List<TestResourcePool> poolList = testResourcePoolMapper.selectByExample(poolExample);
Map<String, String> poolMaps = poolList.stream().collect(Collectors.toMap(TestResourcePool::getId, TestResourcePool::getName));
return poolMaps;
}
/** /**
* 计算任务通过率和执行进度 * 计算任务通过率和执行进度
* *
@ -455,23 +475,57 @@ public class BaseTaskHubService {
*/ */
public void stopTask(String id, String userId, String orgId, String projectId) { public void stopTask(String id, String userId, String orgId, String projectId) {
//1.更新任务状态 //1.更新任务状态
ExecTask execTask = new ExecTask(); extExecTaskMapper.batchUpdateTaskStatus(List.of(id), userId, orgId, projectId, ExecStatus.STOPPED.name());
execTask.setId(id);
execTask.setStatus(ExecStatus.STOPPED.name());
execTask.setCreateUser(userId);
execTask.setProjectId(projectId);
execTask.setOrganizationId(orgId);
extExecTaskMapper.updateTaskStatus(execTask);
//2.更新任务明细状态 //2.更新任务明细状态
ExecTaskItemExample itemExample = new ExecTaskItemExample(); extExecTaskItemMapper.batchUpdateTaskItemStatus(List.of(id), userId, orgId, projectId, ExecStatus.STOPPED.name());
itemExample.createCriteria().andTaskIdEqualTo(id).andStatusEqualTo(ExecStatus.RUNNING.name()); handleStopTask(List.of(id));
ExecTaskItem execTaskItem = new ExecTaskItem(); }
execTaskItem.setStatus(ExecStatus.STOPPED.name());
execTaskItem.setExecutor(userId);
execTaskItemMapper.updateByExampleSelective(execTaskItem, itemExample);
//TODO 3.调用jmeter触发停止
private void handleStopTask(List<String> ids) {
//获取详情资源池
List<ExecTaskItem> list = extExecTaskItemMapper.getResourcePoolsByTaskIds(ids);
Map<String, List<ExecTaskItem>> resourcePoolMaps = list.stream().collect(Collectors.groupingBy(ExecTaskItem::getResourcePoolId));
resourcePoolMaps.forEach((k, v) -> {
//判断资源池类型
TestResourcePoolReturnDTO testResourcePoolDTO = testResourcePoolService.getTestResourcePoolDetail(k);
boolean isK8SResourcePool = StringUtils.equals(testResourcePoolDTO.getType(), ResourcePoolTypeEnum.K8S.getName());
if (isK8SResourcePool) {
List<String> taskIds = list.stream().map(ExecTaskItem::getTaskId).distinct().toList();
//K8S
handleK8STask(taskIds, testResourcePoolDTO);
} else {
Map<String, List<ExecTaskItem>> nodeItem = list.stream().collect(Collectors.groupingBy(ExecTaskItem::getResourcePoolNode));
handleNodeTask(nodeItem);
}
});
}
private void handleNodeTask(Map<String, List<ExecTaskItem>> nodeItem) {
//通过任务向节点发起停止
nodeItem.forEach((node, items) -> {
String endpoint = "http://".concat(node);
List<String> itemIds = items.stream().map(ExecTaskItem::getId).toList();
SubListUtils.dealForSubList(itemIds, 100, subList -> {
try {
LogUtils.info(String.format("开始发送停止请求到 %s 节点执行", endpoint), subList.toString());
MsHttpClient.stopApiTaskItem(endpoint, subList);
} catch (Exception e) {
}
});
});
}
private void handleK8STask(List<String> taskIds, TestResourcePoolReturnDTO testResourcePoolDTO) {
SubListUtils.dealForSubList(taskIds, 100, subList -> {
try {
TestResourceDTO testResourceDTO = new TestResourceDTO();
BeanUtils.copyBean(testResourceDTO, testResourcePoolDTO.getTestResourceReturnDTO());
EngineFactory.stopApiTask(subList, testResourceDTO);
} catch (Exception e) {
LogUtils.error(e);
}
});
} }
public void deleteTask(String id, String orgId, String projectId) { public void deleteTask(String id, String orgId, String projectId) {
@ -483,4 +537,28 @@ public class BaseTaskHubService {
execTaskItemMapper.deleteByExample(itemExample); execTaskItemMapper.deleteByExample(itemExample);
//TODO jmeter执行队列中移除 //TODO jmeter执行队列中移除
} }
public void batchStopTask(TableBatchProcessDTO request, String userId, String orgId, String projectId) {
List<String> ids = getTaskIds(request);
if (CollectionUtils.isNotEmpty(ids)) {
//1.更新任务状态
extExecTaskMapper.batchUpdateTaskStatus(ids, userId, orgId, projectId, ExecStatus.STOPPED.name());
//2.更新任务明细状态
extExecTaskItemMapper.batchUpdateTaskItemStatus(ids, userId, orgId, projectId, ExecStatus.STOPPED.name());
handleStopTask(ids);
}
}
public List<String> getTaskIds(TableBatchProcessDTO request) {
if (request.isSelectAll()) {
List<String> ids = extExecTaskMapper.getIds(request);
if (CollectionUtils.isNotEmpty(request.getExcludeIds())) {
ids.removeAll(request.getExcludeIds());
}
return ids;
} else {
return request.getSelectIds();
}
}
} }

View File

@ -6,7 +6,9 @@ import io.metersphere.system.controller.handler.ResultHolder;
import io.metersphere.system.domain.ExecTask; import io.metersphere.system.domain.ExecTask;
import io.metersphere.system.domain.ExecTaskItem; import io.metersphere.system.domain.ExecTaskItem;
import io.metersphere.system.dto.sdk.BasePageRequest; import io.metersphere.system.dto.sdk.BasePageRequest;
import io.metersphere.system.dto.table.TableBatchProcessDTO;
import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest; import io.metersphere.system.dto.taskhub.request.TaskHubItemRequest;
import io.metersphere.system.mapper.TestResourcePoolMapper;
import io.metersphere.system.service.BaseTaskHubService; import io.metersphere.system.service.BaseTaskHubService;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
@ -27,6 +29,8 @@ public class BaseTaskHubControllerTests extends BaseTest {
@Resource @Resource
private BaseTaskHubService baseTaskHubService; private BaseTaskHubService baseTaskHubService;
@Resource
private TestResourcePoolMapper testResourcePoolMapper;
/** /**
* 系统任务中心测试用例 * 系统任务中心测试用例
@ -39,6 +43,7 @@ public class BaseTaskHubControllerTests extends BaseTest {
public static final String SYSTEM_RESOURCE_POOL_STATUS = "/system/task-center/resource-pool/status"; public static final String SYSTEM_RESOURCE_POOL_STATUS = "/system/task-center/resource-pool/status";
public static final String SYSTEM_TASK_STOP = "/system/task-center/exec-task/stop/"; public static final String SYSTEM_TASK_STOP = "/system/task-center/exec-task/stop/";
public static final String SYSTEM_TASK_DELETE = "/system/task-center/exec-task/delete/"; public static final String SYSTEM_TASK_DELETE = "/system/task-center/exec-task/delete/";
public static final String SYSTEM_TASK_BATCH_STOP = "/system/task-center/exec-task/batch-stop/";
@Test @Test
@Order(1) @Order(1)
@ -146,7 +151,8 @@ public class BaseTaskHubControllerTests extends BaseTest {
@Test @Test
@Order(4) @Order(4)
public void systemTaskStop() throws Exception { public void systemTaskStop() throws Exception {
MvcResult mvcResult = this.requestGetWithOkAndReturn(SYSTEM_TASK_STOP + "1"); this.requestGet(SYSTEM_TASK_STOP + "1");
MvcResult mvcResult = this.requestGetWithOkAndReturn(SYSTEM_TASK_STOP + "2");
// 获取返回值 // 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
@ -159,7 +165,7 @@ public class BaseTaskHubControllerTests extends BaseTest {
* 系统执行任务删除 * 系统执行任务删除
*/ */
@Test @Test
@Order(4) @Order(7)
public void systemTaskDelete() throws Exception { public void systemTaskDelete() throws Exception {
MvcResult mvcResult = this.requestGetWithOkAndReturn(SYSTEM_TASK_DELETE + "4"); MvcResult mvcResult = this.requestGetWithOkAndReturn(SYSTEM_TASK_DELETE + "4");
// 获取返回值 // 获取返回值
@ -170,6 +176,21 @@ public class BaseTaskHubControllerTests extends BaseTest {
} }
/**
* 系统执行任务停止
*/
@Test
@Order(5)
public void systemTaskBatchStop() throws Exception {
TableBatchProcessDTO request = new TableBatchProcessDTO();
request.setSelectAll(true);
this.requestPost(SYSTEM_TASK_BATCH_STOP, request);
request.setSelectAll(false);
request.setSelectIds(List.of("1", "2"));
this.requestPost(SYSTEM_TASK_BATCH_STOP, request);
}
/** /**
* 组织任务中心测试用例 * 组织任务中心测试用例
*/ */
@ -266,21 +287,24 @@ public class BaseTaskHubControllerTests extends BaseTest {
* 组织执行任务停止 * 组织执行任务停止
*/ */
@Test @Test
@Order(4) @Order(24)
public void orgTaskStop() throws Exception { public void orgTaskStop() throws Exception {
MvcResult mvcResult = this.requestGetWithOkAndReturn(ORG_TASK_STOP + "1"); this.requestGet(SYSTEM_TASK_STOP + "1");
MvcResult mvcResult = this.requestGetWithOkAndReturn(ORG_TASK_STOP + "2");
// 获取返回值 // 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常 // 返回请求正常
Assertions.assertNotNull(resultHolder); Assertions.assertNotNull(resultHolder);
testResourcePoolMapper.deleteByPrimaryKey("1");
testResourcePoolMapper.deleteByPrimaryKey("2");
} }
/** /**
* 组织执行任务删除 * 组织执行任务删除
*/ */
@Test @Test
@Order(5) @Order(25)
public void orgTaskDelete() throws Exception { public void orgTaskDelete() throws Exception {
MvcResult mvcResult = this.requestGetWithOkAndReturn(ORG_TASK_DELETE + "4"); MvcResult mvcResult = this.requestGetWithOkAndReturn(ORG_TASK_DELETE + "4");
// 获取返回值 // 获取返回值
@ -291,7 +315,6 @@ public class BaseTaskHubControllerTests extends BaseTest {
} }
@Test @Test
@Order(21) @Order(21)
public void testInsert() throws Exception { public void testInsert() throws Exception {

View File

@ -19,4 +19,12 @@ VALUES
INSERT INTO `exec_task_item`(`id`, `task_id`, `resource_id`, `resource_name`, `task_origin`, `status`, `result`, `resource_pool_id`, `resource_pool_node`, `resource_type`, `project_id`, `organization_id`, `thread_id`, `start_time`, `end_time`, `executor`) INSERT INTO `exec_task_item`(`id`, `task_id`, `resource_id`, `resource_name`, `task_origin`, `status`, `result`, `resource_pool_id`, `resource_pool_node`, `resource_type`, `project_id`, `organization_id`, `thread_id`, `start_time`, `end_time`, `executor`)
VALUES ('1', '1', '1', '1', '1', 'SUCCESS', 'SUCCESS', '1', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin'); VALUES
('1', '1', '1', '1', '1', 'SUCCESS', 'SUCCESS', '1', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin'),
('2', '2', '1', '2', '3', 'SUCCESS', 'SUCCESS', '2', '1', 'API_CASE', '100001100001', '100001', '1', NULL, NULL, 'admin');
INSERT INTO `test_resource_pool` (`id`, `name`, `type`, `description`, `enable`, `create_time`, `update_time`, `create_user`, `server_url`, `all_org`, `deleted`)
VALUES
('1', 'LOCAL', 'Node', '测试资源池', b'1', 1705894549000, 1705894549000, 'admin', NULL, b'1', b'0'),
('2', 'LOCAL', 'Kubernetes', 'Kubernetes测试资源池', b'1', 1705894549000, 1705894549000, 'admin', NULL, b'1', b'0');