1. application.yml修改为application-dev.yml和application-prod.yml

2. 添加更多Exception拦截器
3. 编写状态模式处理task状态的更改
4. 添加StateChangeService,用以处理所有任务状态转换相关的内容
5. 添加StateEnum, ProtocolEnum,TaskTypeEnum用以处理任务和协议相关的所有状态和类型
This commit is contained in:
EnderByEndera
2024-01-11 19:49:07 +08:00
parent 930ba8b5ac
commit 0f712618f2
70 changed files with 1209 additions and 400 deletions

View File

@@ -0,0 +1,22 @@
package com.realtime.protection.server.command;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.realtime.protection.configuration.entity.task.Command;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@DS("doris")
@Mapper
public interface CommandMapper {
Boolean createCommand(@Param("command") Command command);
void createCommands(@Param("commands") List<Command> commands);
Boolean stopCommandsByTaskId(@Param("task_id") Long taskId);
Boolean removeCommandsByTaskId(@Param("task_id") Long taskId);
Boolean startCommandsByTaskId(@Param("task_id") Long taskId);
}

View File

@@ -0,0 +1,101 @@
package com.realtime.protection.server.command;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.task.Command;
import com.realtime.protection.configuration.entity.task.TaskCommandInfo;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
@Service
@Slf4j
public class CommandService {
private final CommandMapper commandMapper;
private final SqlSessionWrapper sqlSessionWrapper;
private static final int BatchSize = 1000;
private final Function<CommandMapper, Function<TaskCommandInfo, Void>> createCommandBatchFunction;
public CommandService(CommandMapper commandMapper, SqlSessionWrapper sqlSessionWrapper) {
this.commandMapper = commandMapper;
this.sqlSessionWrapper = sqlSessionWrapper;
this.createCommandBatchFunction = mapper -> info -> {
if (info.getFrequency() == null) {
Command command = Command.generateCommand(info, info.getStartTime());
commandMapper.createCommand(command);
}
List<Command> commandBatch = ListUtils.newArrayListWithExpectedSize(BatchSize);
LocalDateTime validTime = info.getStartTime();
while (validTime.isBefore(info.getEndTime())) {
Command command = Command.generateCommand(info, validTime);
commandBatch.add(command);
validTime = validTime.plusMinutes(info.getFrequency());
if (commandBatch.size() < BatchSize) {
continue;
}
commandMapper.createCommands(commandBatch);
commandBatch.clear();
}
if (!commandBatch.isEmpty()) {
commandMapper.createCommands(commandBatch);
commandBatch.clear();
}
log.debug(String.format("create all the commands from task(%d), rule(%d)",
info.getTaskId(), info.getRuleId()));
return null;
};
}
@Async
public void createCommand(TaskCommandInfo commandInfo) throws DorisStartException {
try {
sqlSessionWrapper.startBatchSession(CommandMapper.class, createCommandBatchFunction, commandInfo);
} catch (Exception e) {
throw new DorisStartException(e);
}
}
@Async
public void createCommands(List<TaskCommandInfo> taskCommandInfos) throws DorisStartException {
Function<CommandMapper, Function<List<TaskCommandInfo>, Void>> function = mapper -> list -> {
if (list == null || list.isEmpty()) {
return null;
}
for (TaskCommandInfo info : list) {
createCommandBatchFunction.apply(mapper).apply(info);
}
return null;
};
try {
sqlSessionWrapper.startBatchSession(CommandMapper.class, function, taskCommandInfos);
} catch (Exception e) {
throw new DorisStartException(e);
}
}
public Boolean startCommandsByTaskId(Long taskId) {
return commandMapper.startCommandsByTaskId(taskId);
}
public Boolean stopCommandsByTaskId(Long taskId) {
return commandMapper.stopCommandsByTaskId(taskId);
}
public Boolean removeCommandsByTaskId(Long taskId) {
return commandMapper.removeCommandsByTaskId(taskId);
}
}

View File

@@ -3,6 +3,7 @@ package com.realtime.protection.server.defense.object;
import com.alibaba.excel.EasyExcel;
import com.realtime.protection.configuration.entity.defense.object.ProtectObject;
import com.realtime.protection.configuration.response.ResponseResult;
import com.realtime.protection.configuration.utils.EntityUtils;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
@@ -76,21 +77,15 @@ public class ProtectObjectController {
}
@GetMapping("/{id}/query")
public ResponseResult queryProtectObject(@PathVariable("id") Integer protectObjectId) {
@GetMapping("/{protectObjectId}/query")
public ResponseResult queryProtectObject(@PathVariable Integer protectObjectId) throws IllegalAccessException {
ProtectObject protectObject = protectObjectService.queryProtectObject(protectObjectId);
return ResponseResult.ok()
.setData("proobj_id", protectObject.getProtectObjectId())
.setData("proobj_name", protectObject.getProtectObjectName())
.setData("proobj_system_name", protectObject.getProtectObjectSystemName())
.setData("proobj_ip_address", protectObject.getProtectObjectIPAddress())
.setData("proobj_port", protectObject.getProtectObjectPort())
.setData("proobj_url", protectObject.getProtectObjectURL())
.setData("proobj_protocol", protectObject.getProtectObjectProtocol());
.setDataMap(EntityUtils.entityToMap(protectObject));
}
@PostMapping("/{id}/update")
public ResponseResult updateProtectObject(@PathVariable("id") Integer protectObjectId,
@PostMapping("/{protectObjectId}/update")
public ResponseResult updateProtectObject(@PathVariable Integer protectObjectId,
@RequestBody @Valid ProtectObject protectObject) {
protectObject.setProtectObjectId(protectObjectId);
return ResponseResult.ok()
@@ -98,8 +93,8 @@ public class ProtectObjectController {
.setData("success", protectObjectService.updateProtectObject(protectObject));
}
@DeleteMapping("/{id}/delete")
public ResponseResult deleteProtectObject(@PathVariable("id") Integer protectObjectId) {
@DeleteMapping("/{protectObjectId}/delete")
public ResponseResult deleteProtectObject(@PathVariable Integer protectObjectId) {
return ResponseResult.ok()
.setData("proobj_id", protectObjectId)
.setData("success", protectObjectService.deleteProtectObject(protectObjectId));
@@ -112,9 +107,9 @@ public class ProtectObjectController {
.setData("success", protectObjectService.deleteProtectObjects(protectObjectIds));
}
@PostMapping("/{id}/audit/{status}")
public ResponseResult changeProtectObjectAuditStatus(@PathVariable("id") Integer protectObjectId,
@PathVariable("status") Integer auditStatus) {
@PostMapping("/{protectObjectId}/audit/{auditStatus}")
public ResponseResult changeProtectObjectAuditStatus(@PathVariable Integer protectObjectId,
@PathVariable Integer auditStatus) {
return ResponseResult.ok()
.setDataMap(protectObjectService.changeProtectObjectAuditStatus(protectObjectId, auditStatus))
.setData("proobj_id", protectObjectId);

View File

@@ -2,8 +2,8 @@ package com.realtime.protection.server.defense.object;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.defense.object.ProtectObject;
import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -90,7 +90,7 @@ public class ProtectObjectService {
protectObjectBatch.clear();
}
if (!protectObjectBatch.isEmpty()) {
mapper.deleteProtectObjects(protectObjectBatch);;
mapper.deleteProtectObjects(protectObjectBatch);
}
return success;
};

View File

@@ -2,6 +2,7 @@ package com.realtime.protection.server.defense.template;
import com.realtime.protection.configuration.entity.defense.template.Template;
import com.realtime.protection.configuration.response.ResponseResult;
import com.realtime.protection.configuration.utils.EntityUtils;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import org.springframework.web.bind.annotation.*;
@@ -43,16 +44,22 @@ public class TemplateController {
@GetMapping("/query")
public ResponseResult queryTemplates(@RequestParam(value = "template_name", required = false) String templateName,
@RequestParam("page") @Min(1) Integer page,
@RequestParam("page_size") @Min(1) Integer pageSize) {
@RequestParam("page") @Min(1) Integer page,
@RequestParam("page_size") @Min(1) Integer pageSize) {
List<Template> templates = templateService.queryTemplates(templateName, page, pageSize);
return ResponseResult.ok()
.setData("templates", templates);
}
@PostMapping("/{id}/update")
public ResponseResult updateTemplate(@PathVariable("id") @Min(1) Integer templateId,
@GetMapping("/{templateId}/query")
public ResponseResult queryTemplate(@PathVariable Integer templateId) throws IllegalAccessException {
return ResponseResult.ok()
.setDataMap(EntityUtils.entityToMap(templateService.queryTemplate(templateId)));
}
@PostMapping("/{templateId}/update")
public ResponseResult updateTemplate(@PathVariable @Min(1) Integer templateId,
@RequestBody @Valid Template template) {
Boolean success = templateService.updateTemplate(templateId, template);
return ResponseResult.ok()
@@ -60,14 +67,10 @@ public class TemplateController {
.setData("success", success);
}
@GetMapping("/{id}/addUsedTimes")
public ResponseResult addTemplateUsedTimes(@PathVariable("id") @Min(1) Integer templateId,
@RequestParam(value = "add_num") @Min(0) Integer addNum) {
Boolean success = templateService.addTemplateUsedTimes(templateId, addNum);
@DeleteMapping("/{templateId}/delete")
public ResponseResult deleteTemplate(@PathVariable @Min(1) Integer templateId) {
return ResponseResult.ok()
.setData("template_id", templateId)
.setData("success", success);
.setData("success", templateService.deleteTemplate(templateId));
}
}

View File

@@ -21,7 +21,7 @@ public interface TemplateMapper {
Boolean updateTemplateInformation(@Param("template") Template template);
void countTemplateRunningTasks(@Param("template_id") Integer templateId);
Template queryTemplate(@Param("template_id") Integer templateId);
Boolean addTemplateUsedTimes(@Param("template_id") Integer templateId, @Param("add_times") Integer addTimes);
Boolean deleteTemplate(@Param("template_id") Integer templateId);
}

View File

@@ -4,8 +4,6 @@ import com.realtime.protection.configuration.entity.defense.template.Template;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.beans.Transient;
import java.util.Arrays;
import java.util.List;
@Service
@@ -41,8 +39,11 @@ public class TemplateService {
return templateMapper.updateTemplateInformation(template);
}
public Boolean addTemplateUsedTimes(Integer templateId, Integer addTimes) {
return templateMapper.addTemplateUsedTimes(templateId, addTimes);
public Template queryTemplate(Integer templateId) {
return templateMapper.queryTemplate(templateId);
}
public Boolean deleteTemplate(Integer templateId) {
return templateMapper.deleteTemplate(templateId);
}
}

View File

@@ -43,11 +43,9 @@ public class DynamicRuleController {
}
//id删除
@RequestMapping("/{dynamicRuleId}/delete")
public ResponseResult deleteDynamicRuleObject(@PathVariable Integer dynamicRuleId ) {
public ResponseResult deleteDynamicRuleObject(@PathVariable Integer dynamicRuleId) {
log.info("删除动态规则: {}", dynamicRuleId);
//调用service删除
dynamicRuleService.deleteDynamicRuleObject(dynamicRuleId);
@@ -62,7 +60,7 @@ public class DynamicRuleController {
//调用service删除
return ResponseResult.ok()
.setData("success",dynamicRuleService.deleteDynamicRuleObjects(dynamicRuleIds));
.setData("success", dynamicRuleService.deleteDynamicRuleObjects(dynamicRuleIds));
}
//修改

View File

@@ -4,7 +4,6 @@ import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.rule.dynamicrule.DynamicRuleObject;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

View File

@@ -16,13 +16,13 @@ public interface DynamicRuleMapper {
//新建动态规则与保护对象关联
void newDynamicRulProtectObjectConcat(long dynamicRuleId, Integer protectObjectId);
void deleteDynamicRuleObject( Integer dynamicRuleId);
void deleteDynamicRuleObject(Integer dynamicRuleId);
DynamicRuleObject queryDynamicRuleById(Integer dynamicRuleId);
List<ProtectObject> queryProtectObjectByRuleId(Integer dynamicRuleId);
void updateDynamicRuleObject(@Param("dynamicRuleId") Integer dynamicRuleId,@Param("object") DynamicRuleObject dynamicRuleObject);
void updateDynamicRuleObject(@Param("dynamicRuleId") Integer dynamicRuleId, @Param("object") DynamicRuleObject dynamicRuleObject);
void newDynamicRules(List<DynamicRuleObject> dynamicRuleObjects);

View File

@@ -6,8 +6,8 @@ import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleOb
import com.realtime.protection.configuration.response.ResponseResult;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@@ -22,6 +22,7 @@ import java.util.List;
public class StaticRuleController {
private final StaticRuleService staticRuleService;
public StaticRuleController(StaticRuleService staticRuleService) {
this.staticRuleService = staticRuleService;
}
@@ -30,11 +31,11 @@ public class StaticRuleController {
* 新增静态规则
*/
@PostMapping("/new")
public ResponseResult newStaticRuleObject(@RequestBody @Valid StaticRuleObject object){
log.info("新增静态规则: {}" , object);
public ResponseResult newStaticRuleObject(@RequestBody @Valid StaticRuleObject object) {
log.info("新增静态规则: {}", object);
//调用service新增
staticRuleService.newStaticRuleObject(object);
return ResponseResult.ok().setData("static_rule_name",object.getStaticRuleName());
return ResponseResult.ok().setData("static_rule_name", object.getStaticRuleName());
}
//以Excel方式批量导入静态规则
@@ -44,6 +45,7 @@ public class StaticRuleController {
new StaticRuleDataListener(staticRuleService)).sheet().doRead();
return ResponseResult.ok();
}
//下载模板文件
@GetMapping("/download")
public void downloadTemplate(HttpServletResponse response) throws IOException {
@@ -62,20 +64,20 @@ public class StaticRuleController {
* 删除静态规则有的删了有的没删也返回false
*/
@DeleteMapping("/{ids}")
public ResponseResult delete(@PathVariable List<Integer> ids){
log.info("根据id删除静态规则:{}",ids);
//
public ResponseResult delete(@PathVariable List<Integer> ids) {
log.info("根据id删除静态规则:{}", ids);
//
return ResponseResult.ok()
.setData("static_rule_id",ids)
.setData("success",staticRuleService.deleteStaticRules(ids));
.setData("static_rule_id", ids)
.setData("success", staticRuleService.deleteStaticRules(ids));
}
/**
* 修改静态规则
*/
@PutMapping("/update")
public ResponseResult updateStaticRule(@RequestBody @Valid StaticRuleObject object){
log.info("修改静态规则: {}" , object);
public ResponseResult updateStaticRule(@RequestBody @Valid StaticRuleObject object) {
log.info("修改静态规则: {}", object);
//调用service修改
staticRuleService.updateStaticRule(object);
return ResponseResult.ok();
@@ -86,11 +88,11 @@ public class StaticRuleController {
* 路径参数通过请求URL直接传递参数使用{…}来标识该路径参数,需要使用 @PathVariable 获取路径参数
*/
@RequestMapping("/{id}/query")
public ResponseResult queryStaticRuleById(@PathVariable Integer id){
log.info("根据id查询静态规则:{}",id);
StaticRuleObject object = staticRuleService.queryStaticRuleById(id);
return ResponseResult.ok().setData("static_rule",object);
}
public ResponseResult queryStaticRuleById(@PathVariable Integer id) {
log.info("根据id查询静态规则:{}", id);
StaticRuleObject object = staticRuleService.queryStaticRuleById(id);
return ResponseResult.ok().setData("static_rule", object);
}
/**
* 分页查询静态规则
@@ -99,10 +101,10 @@ public class StaticRuleController {
public ResponseResult queryStaticRule(String static_rule_name, Integer static_rule_id,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer pageSize
){
log.info("多查询静态规则: {},{},{},{}", static_rule_name,static_rule_id,page,pageSize);
) {
log.info("多查询静态规则: {},{},{},{}", static_rule_name, static_rule_id, page, pageSize);
//调用service新增
List<StaticRuleObject> pageResult = staticRuleService.queryStaticRule(static_rule_name,static_rule_id,page,pageSize);
return ResponseResult.ok().setData("static_rule_list",pageResult);
List<StaticRuleObject> pageResult = staticRuleService.queryStaticRule(static_rule_name, static_rule_id, page, pageSize);
return ResponseResult.ok().setData("static_rule_list", pageResult);
}
}

View File

@@ -6,7 +6,6 @@ import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
@Slf4j

View File

@@ -16,8 +16,6 @@ public interface StaticRuleMapper {
//根据主键删除静态规则
@Delete("delete from t_static_rule where static_rule_id = #{id}")
Boolean deleteStaticRuleById(Integer id);
//修改静态规则

View File

@@ -2,9 +2,8 @@ package com.realtime.protection.server.rule.staticrule;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject;
import org.springframework.stereotype.Service;
import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@@ -88,7 +87,7 @@ public class StaticRuleService {
*/
public List<StaticRuleObject> queryStaticRule(String static_rule_name, Integer static_rule_id, Integer page, Integer pageSize) {
return staticRuleMapper.queryStaticRule(static_rule_name,static_rule_id,page,pageSize);
return staticRuleMapper.queryStaticRule(static_rule_name, static_rule_id, page, pageSize);
}
public Boolean newStaticRuleObjects(List<StaticRuleObject> staticRuleList) {

View File

@@ -1,20 +0,0 @@
package com.realtime.protection.server.task;
import com.realtime.protection.server.task.state.State;
public class StatusChanger {
private final State state;
public StatusChanger(State state) {
this.state = state;
}
public static StatusChanger setOriginal(State original) {
return new StatusChanger(original);
}
public Boolean changeState(State newState) {
return this.state.handle(newState);
}
}

View File

@@ -1,9 +1,14 @@
package com.realtime.protection.server.task;
import com.realtime.protection.configuration.entity.task.Task;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.response.ResponseResult;
import com.realtime.protection.configuration.utils.EntityUtils;
import com.realtime.protection.server.task.status.StateChangeService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -13,14 +18,16 @@ import java.util.List;
public class TaskController {
private final TaskService taskService;
private final StateChangeService stateChangeService;
public TaskController(TaskService taskService) {
public TaskController(TaskService taskService, StateChangeService stateChangeService) {
this.taskService = taskService;
this.stateChangeService = stateChangeService;
}
@PostMapping("/new")
public ResponseResult newTask(@RequestBody @Valid Task task) {
Integer taskId = taskService.newTask(task);
Long taskId = taskService.newTask(task);
if (taskId > 0) {
return ResponseResult.ok()
@@ -48,7 +55,7 @@ public class TaskController {
}
@GetMapping("/{id}/query")
public ResponseResult queryTask(@PathVariable("id") @Min(1) Integer id) {
public ResponseResult queryTask(@PathVariable @Min(1) Long id) throws IllegalAccessException {
Task task = taskService.queryTask(id);
if (task == null) {
@@ -56,44 +63,39 @@ public class TaskController {
}
return ResponseResult.ok()
.setData("task_id", task.getTaskId())
.setData("task_name", task.getTaskName())
.setData("task_type", task.getTaskType())
.setData("task_status", task.getTaskStatus())
.setData("task_creator", task.getTaskCreateUsername())
.setData("task_creator_depart", task.getTaskCreateDepart())
.setData("task_start_time", task.getTaskStartTime())
.setData("task_end_time", task.getTaskEndTime())
.setData("task_static_rule_ids", task.getStaticRuleIds())
.setData("task_dynamic_rule_ids", task.getDynamicRuleIds());
.setDataMap(EntityUtils.entityToMap(task));
}
@PostMapping("/{id}/update")
public ResponseResult updateTask(@PathVariable("id") @Min(1) Integer taskId, @RequestBody @Valid Task task) {
task.setTaskId(taskId);
@PostMapping("/update")
public ResponseResult updateTask(@RequestBody @Valid Task task) {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("task_id", task.getTaskId())
.setData("success", taskService.updateTask(task));
}
@GetMapping("/{taskId}/audit/{auditStatus}")
public ResponseResult changeTaskAuditStatus(@PathVariable Integer auditStatus, @PathVariable Integer taskId) {
public ResponseResult changeTaskAuditStatus(@PathVariable @NotNull @Max(10) Integer auditStatus,
@PathVariable @NotNull @Min(1) Long taskId) {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("success", taskService.changeTaskAuditStatus(taskId, auditStatus));
.setData("success", taskService.changeTaskAuditStatus(taskId, auditStatus))
.setData("audit_status", taskService.queryTaskAuditStatus(taskId));
}
@GetMapping("/{id}/delete")
public ResponseResult deleteTask(@PathVariable("id") Integer taskId) {
@GetMapping("/{taskId}/delete")
public ResponseResult deleteTask(@PathVariable @NotNull @Min(1) Long taskId) {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("success", taskService.deleteTask(taskId));
}
@GetMapping("/{taskId}/running/{state}")
public ResponseResult changeTaskStatus(@PathVariable Integer state, @PathVariable Integer taskId) {
@GetMapping("/{taskId}/running/{stateNum}")
public ResponseResult changeTaskStatus(@PathVariable @NotNull Integer stateNum,
@PathVariable @NotNull Long taskId) throws DorisStartException {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("success", taskService.changeTaskStatus(taskId, state));
.setData("success", stateChangeService.changeState(stateNum, taskId))
.setData("status_now", taskService.queryTaskStatus(taskId));
}
}

View File

@@ -1,6 +1,7 @@
package com.realtime.protection.server.task;
import com.realtime.protection.configuration.entity.task.Task;
import com.realtime.protection.configuration.entity.task.TaskCommandInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -10,25 +11,33 @@ import java.util.List;
public interface TaskMapper {
void newTask(@Param("task") Task task);
void newTaskStaticRuleConcat(@Param("task_id") Integer taskId,
@Param("rule_ids") List<Integer> staticRuleIds);
void newTaskStaticRuleConcat(@Param("task_id") Long taskId,
@Param("rule_ids") List<Long> staticRuleIds);
void newTaskDynamicRuleConcat(@Param("task_id") Integer taskId,
@Param("rule_ids") List<Integer> dynamicRuleIds);
void newTaskDynamicRuleConcat(@Param("task_id") Long taskId,
@Param("rule_ids") List<Long> dynamicRuleIds);
List<Task> queryTasks(@Param("task_status") Integer taskStatus, @Param("task_type") String task_type,
@Param("task_name") String taskName, @Param("task_creator") String taskCreator,
@Param("page") Integer page, @Param("page_size") Integer pageSize);
Task queryTask(@Param("task_id") Integer taskId);
Task queryTask(@Param("task_id") Long taskId);
void updateTask(@Param("task") Task task);
void clearTaskConnectedStaticRule(@Param("task_id") Integer taskId);
void clearTaskConnectedStaticRule(@Param("task_id") Long taskId);
void clearTaskConnectedDynamicRule(@Param("task_id") Integer taskId);
void clearTaskConnectedDynamicRule(@Param("task_id") Long taskId);
void changeTaskAuditStatus(@Param("task_id") Integer taskId, @Param("audit_status") Integer auditStatus);
void changeTaskAuditStatus(@Param("task_id") Long taskId, @Param("audit_status") Integer auditStatus);
Boolean deleteTask(@Param("task_id") Integer taskId);
Boolean deleteTask(@Param("task_id") Long taskId);
Boolean changeTaskStatus(@Param("task_id") Long taskId, @Param("state") Integer stateNum);
List<TaskCommandInfo> getStaticCommands(@Param("task_id") Long taskId);
Integer queryTaskAuditStatus(@Param("task_id") Long taskId);
Integer queryTaskStatus(@Param("task_id") Long taskId);
}

View File

@@ -1,11 +1,8 @@
package com.realtime.protection.server.task;
import com.realtime.protection.configuration.entity.task.Task;
import com.realtime.protection.configuration.entity.task.TaskCommandInfo;
import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.server.task.state.PauseState;
import com.realtime.protection.server.task.state.RunningState;
import com.realtime.protection.server.task.state.State;
import com.realtime.protection.server.task.state.StopState;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -20,7 +17,7 @@ public class TaskService {
}
@Transactional
public Integer newTask(Task task) {
public Long newTask(Task task) {
taskMapper.newTask(task);
taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
@@ -35,7 +32,7 @@ public class TaskService {
return taskMapper.queryTasks(taskStatus, taskType, taskName, taskCreator, page, pageSize);
}
public Task queryTask(Integer id) {
public Task queryTask(Long id) {
return taskMapper.queryTask(id);
}
@@ -46,47 +43,46 @@ public class TaskService {
taskMapper.clearTaskConnectedStaticRule(task.getTaskId());
taskMapper.clearTaskConnectedDynamicRule(task.getTaskId());
taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds());
if (task.getStaticRuleIds() != null && !task.getStaticRuleIds().isEmpty())
taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
if (task.getDynamicRuleIds() != null && !task.getDynamicRuleIds().isEmpty())
taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds());
return true;
}
@Transactional
public Boolean changeTaskAuditStatus(Integer taskId, Integer taskAuditStatus) {
if (AuditStatusValidator.setOriginal(taskMapper.queryTask(taskId).getTaskAuditStatus()).checkValidate(taskAuditStatus))
public Boolean changeTaskAuditStatus(Long taskId, Integer taskAuditStatus) {
Integer originalAuditStatus = taskMapper.queryTaskAuditStatus(taskId);
if (originalAuditStatus == null) {
throw new IllegalArgumentException("cannot find audit status of task " + taskId + ", maybe task doesn't exist?");
}
if (AuditStatusValidator.setOriginal(originalAuditStatus).checkValidate(taskAuditStatus))
taskMapper.changeTaskAuditStatus(taskId, taskAuditStatus);
else return false;
return true;
}
public Boolean deleteTask(Integer taskId) {
public Boolean deleteTask(Long taskId) {
return taskMapper.deleteTask(taskId);
}
@Transactional
public Boolean changeTaskStatus(Integer taskId, Integer stateNum) {
State originalState = switch (taskMapper.queryTask(taskId).getTaskStatus()) {
// 运行中
case 1 -> new RunningState();
// 暂停中
case 2 -> new PauseState();
// 停止中
case 3 -> new StopState();
default -> throw new IllegalArgumentException();
};
public Boolean changeTaskStatus(Long taskId, Integer stateNum) {
return taskMapper.changeTaskStatus(taskId, stateNum);
}
State newState = switch (stateNum) {
// 运行中
case 1 -> new RunningState();
// 暂停中
case 2 -> new PauseState();
// 停止中
case 3 -> new StopState();
default -> throw new IllegalArgumentException();
};
public List<TaskCommandInfo> getStaticCommandInfos(Long taskId) {
return taskMapper.getStaticCommands(taskId);
}
return StatusChanger.setOriginal(originalState).changeState(newState);
public Integer queryTaskAuditStatus(Long taskId) {
return taskMapper.queryTaskAuditStatus(taskId);
}
public Integer queryTaskStatus(Long taskId) {
return taskMapper.queryTaskStatus(taskId);
}
}

View File

@@ -1,19 +0,0 @@
package com.realtime.protection.server.task.state;
import com.baomidou.dynamic.datasource.annotation.DS;
public class PauseState implements State {
@Override
public Boolean handle(State newState) {
if (newState instanceof RunningState) {
return handleRun();
}
return false;
}
@DS("oracle")
private Boolean handleRun() {
return true;
}
}

View File

@@ -1,28 +0,0 @@
package com.realtime.protection.server.task.state;
public class RunningState implements State {
@Override
public Boolean handle(State newState) {
if (newState instanceof RunningState) {
return false;
}
if (newState instanceof PauseState) {
return handlePause();
}
if (newState instanceof StopState) {
return handleStop();
}
return false;
}
private Boolean handlePause() {
return true;
}
private Boolean handleStop() {
return true;
}
}

View File

@@ -1,6 +0,0 @@
package com.realtime.protection.server.task.state;
public interface State {
Boolean handle(State newState);
}

View File

@@ -1,8 +0,0 @@
package com.realtime.protection.server.task.state;
import com.realtime.protection.configuration.entity.task.Command;
import org.apache.ibatis.annotations.Param;
public interface StateMapper {
Boolean sendCommand(@Param("command") Command command);
}

View File

@@ -1,17 +0,0 @@
package com.realtime.protection.server.task.state;
public class StopState implements State {
@Override
public Boolean handle(State newState) {
if (newState instanceof RunningState) {
return handleRun();
}
return false;
}
public Boolean handleRun() {
return true;
}
}

View File

@@ -0,0 +1,46 @@
package com.realtime.protection.server.task.status;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class StateChangeService {
private final CommandService commandService;
private final TaskService taskService;
public StateChangeService(CommandService commandService, TaskService taskService) {
this.commandService = commandService;
this.taskService = taskService;
}
@DSTransactional
public Boolean changeState(Integer stateNum, Long taskId) throws DorisStartException {
Integer originalStateNum = taskService.queryTaskStatus(taskId);
if (originalStateNum == null) {
throw new IllegalArgumentException("cannot find status of task " + taskId + ", maybe task doesn't exist?");
}
State originalState = StateEnum.getStateByNum(originalStateNum);
State newState = StateEnum.getStateByNum(stateNum);
if (!originalState.handle(newState, commandService, taskService, taskId)) {
return false;
}
log.debug(String.format("successfully let task(%d) change state from %s to %s",
taskId,
originalState.getClass().getSimpleName(),
newState.getClass().getSimpleName()));
// 这里一定是handle成功的状态我们再进行task status的修改如果handle失败要么返回false要么抛出异常不会进入此处
return taskService.changeTaskStatus(taskId, stateNum);
}
}

View File

@@ -0,0 +1,89 @@
package com.realtime.protection.server.task.status;
import com.realtime.protection.configuration.entity.task.Task;
import com.realtime.protection.configuration.entity.task.TaskCommandInfo;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.enums.TaskTypeEnum;
import com.realtime.protection.configuration.utils.status.AuditStatus;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import java.util.List;
public class StateHandler {
protected Boolean handleStart(TaskService taskService, CommandService commandService, Long taskId) throws DorisStartException {
Task task = taskService.queryTask(taskId);
if (task == null) {
throw new IllegalArgumentException("invalid task id");
}
Integer taskAuditStatus = task.getTaskAuditStatus();
if (taskAuditStatus == null) {
throw new IllegalArgumentException("invalid task id, because task_audit_status is null");
}
// 如果审核状态不为已通过审核,则无效
if (taskAuditStatus != AuditStatus.AUDITED.getAuditStatus()) {
return false;
}
return switch (TaskTypeEnum.getTaskTypeByNum(task.getTaskType())) {
case STATIC -> handleStaticTaskStart(commandService, taskService, taskId);
case DYNAMIC -> handleDynamicTaskStart(commandService, taskService, taskId);
case JUDGED -> handleJudgedTaskStart(commandService, taskService, taskId);
};
}
protected Boolean handleResume(CommandService commandService, Long taskId) {
commandService.startCommandsByTaskId(taskId);
return true;
}
protected Boolean handlePause(CommandService commandService, Long taskId) {
commandService.stopCommandsByTaskId(taskId);
return true;
}
protected Boolean handleStop(CommandService commandService, Long taskId) {
commandService.removeCommandsByTaskId(taskId);
return true;
}
protected Boolean handleFinish(CommandService commandService, Long taskId) {
commandService.removeCommandsByTaskId(taskId);
return true;
}
protected Boolean handleFailed(CommandService commandService, Long taskId) {
commandService.removeCommandsByTaskId(taskId);
return true;
}
private Boolean handleJudgedTaskStart(CommandService commandService, TaskService taskService, Long taskId) {
return true;
}
private Boolean handleDynamicTaskStart(CommandService commandService, TaskService taskService, Long taskId) {
return true;
}
private Boolean handleStaticTaskStart(CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException {
// 如果未能获取staticTaskCommandInfos需要报错
List<TaskCommandInfo> staticTaskCommandInfos = taskService.getStaticCommandInfos(taskId);
if (staticTaskCommandInfos == null || staticTaskCommandInfos.isEmpty()) {
throw new IllegalArgumentException("static rules are empty, need to choose at least one static rule");
}
try {
commandService.createCommands(staticTaskCommandInfos);
} catch (DorisStartException e) {
e.taskId = taskId;
throw e;
}
return true;
}
}

View File

@@ -0,0 +1,20 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import com.realtime.protection.server.task.status.StateHandler;
public class FailedState extends StateHandler implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException {
return switch (StateEnum.getStateEnumByState(newState)) {
case RUNNING -> handleStart(taskService, commandService, taskId);
case STOP -> handleStop(commandService, taskId);
case FAILED -> true;
default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState));
};
}
}

View File

@@ -0,0 +1,12 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
public class FinishedState implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) {
return newState instanceof FinishedState;
}
}

View File

@@ -0,0 +1,20 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import com.realtime.protection.server.task.status.StateHandler;
public class PauseState extends StateHandler implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) {
return switch (StateEnum.getStateEnumByState(newState)) {
case RUNNING -> handleResume(commandService, taskId);
case STOP -> handleStop(commandService, taskId);
case FINISHED -> handleFinish(commandService, taskId);
case FAILED -> handleFailed(commandService, taskId);
default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState));
};
}
}

View File

@@ -0,0 +1,19 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import com.realtime.protection.server.task.status.StateHandler;
public class PendingState extends StateHandler implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException {
return switch (StateEnum.getStateEnumByState(newState)) {
case RUNNING -> handleStart(taskService, commandService, taskId);
case FAILED -> handleFailed(commandService, taskId);
default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState));
};
}
}

View File

@@ -0,0 +1,21 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import com.realtime.protection.server.task.status.StateHandler;
public class RunningState extends StateHandler implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) {
return switch(StateEnum.getStateEnumByState(newState)) {
case RUNNING -> true;
case PAUSED -> handlePause(commandService, taskId);
case STOP -> handleStop(commandService, taskId);
case FINISHED -> handleFinish(commandService, taskId);
case FAILED -> handleFailed(commandService, taskId);
default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState));
};
}
}

View File

@@ -0,0 +1,20 @@
package com.realtime.protection.server.task.status.states;
import com.realtime.protection.configuration.exception.DorisStartException;
import com.realtime.protection.configuration.utils.enums.StateEnum;
import com.realtime.protection.configuration.utils.status.State;
import com.realtime.protection.server.command.CommandService;
import com.realtime.protection.server.task.TaskService;
import com.realtime.protection.server.task.status.StateHandler;
public class StopState extends StateHandler implements State {
@Override
public Boolean handle(State newState, CommandService commandService, TaskService taskService, Long taskId) throws DorisStartException {
return switch (StateEnum.getStateEnumByState(newState)) {
case RUNNING -> handleStart(taskService, commandService, taskId);
case FAILED -> handleFailed(commandService, taskId);
default -> throw new IllegalStateException("Unexpected value: " + StateEnum.getStateEnumByState(newState));
};
}
}

View File

@@ -7,7 +7,6 @@ import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -40,6 +39,7 @@ public class WhiteListController {
new WhiteListDataListener(whiteListService)).sheet().doRead();
return ResponseResult.ok();
}
//下载模板文件
@GetMapping("/download")
public void downloadTemplate(HttpServletResponse response) throws IOException {
@@ -54,10 +54,10 @@ public class WhiteListController {
}
@RequestMapping("/query")
public ResponseResult queryWhiteListObject(@RequestParam(value = "whiteobj_name", required = false)String whiteListName,
@RequestParam(value = "page_size", required = false)Integer whiteListId,
@RequestParam(value = "page", defaultValue = "1")Integer page,
@RequestParam(value = "page_size", defaultValue = "10")Integer pageSize) {
public ResponseResult queryWhiteListObject(@RequestParam(value = "whiteobj_name", required = false) String whiteListName,
@RequestParam(value = "page_size", required = false) Integer whiteListId,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "page_size", defaultValue = "10") Integer pageSize) {
if (page <= 0 || pageSize <= 0) {
return new ResponseResult(400, "page or page_size is invalid")
.setData("whiteobj_list", null);
@@ -103,7 +103,7 @@ public class WhiteListController {
}
@PostMapping("/delete")
public ResponseResult deleteWhiteListObjects( @RequestBody List<Integer> whiteListObjIds) {
public ResponseResult deleteWhiteListObjects(@RequestBody List<Integer> whiteListObjIds) {
//Post不支持body为json。。。 body只能是[9,10]
return ResponseResult.ok()
@@ -111,7 +111,7 @@ public class WhiteListController {
.setData("success", whiteListService.deleteWhiteListObjects(whiteListObjIds));
}
@PostMapping ("/{id}/update")
@PostMapping("/{id}/update")
public ResponseResult updateWhiteListObject(@PathVariable Integer id,
@RequestBody WhiteListObject object) {
object.setWhiteListId(id);
@@ -124,7 +124,6 @@ public class WhiteListController {
}
//查询ip是否存在于白名单
@PostMapping("/exist")
public ResponseResult existWhiteListObject(@RequestBody List<Integer> ruleIds) {
@@ -155,5 +154,4 @@ public class WhiteListController {
}
}

View File

@@ -5,12 +5,11 @@ import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.whitelist.WhiteListObject;
import lombok.extern.slf4j.Slf4j;
//import com.alibaba.fastjson2.JSON;
import java.util.List;
@Slf4j
public class WhiteListDataListener implements ReadListener<WhiteListObject> {
public class WhiteListDataListener implements ReadListener<WhiteListObject> {
private static final int batchCount = 100;
private final List<WhiteListObject> cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);

View File

@@ -13,23 +13,26 @@ public interface WhiteListMapper {
//新建
void newWhiteListObject(@Param("object") WhiteListObject object);
//分页查询
List<WhiteListObject> queryWhiteListObject(String whiteListName, Integer whiteListId, Integer page, Integer pageSize);
//根据主键查询
WhiteListObject queryWhiteListObjectById(Integer id);
//根据主键删除
@Delete("delete from t_white_list where white_list_id = #{id}")
Integer deleteWhiteListObject(Integer id);
Integer updateWhiteListObject(@Param("object") WhiteListObject object);
String existWhiteListObject(@Param("staticRuleObject")StaticRuleObject staticRuleObject);
String existWhiteListObject(@Param("staticRuleObject") StaticRuleObject staticRuleObject);
Integer queryWhiteListObjectAuditStuatusById(Integer id);
Boolean updateWhiteListObjectAuditStatus(Integer id, Integer status);
void newWhiteListObjects(@Param("whiteListObjects")List<WhiteListObject> whiteListBatch);
void newWhiteListObjects(@Param("whiteListObjects") List<WhiteListObject> whiteListBatch);
void deleteWhiteListObjects(@Param("whiteListIds") List<Integer> whiteListBatch);
}

View File

@@ -3,8 +3,8 @@ package com.realtime.protection.server.whitelist;
import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject;
import com.realtime.protection.configuration.entity.whitelist.WhiteListObject;
import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.server.rule.staticrule.StaticRuleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -38,6 +38,7 @@ public class WhiteListService {
return object.getWhiteListId();
}
//批量新建多个whitelist
public Boolean newWhiteListObjects(List<WhiteListObject> whiteListObjectList) {
Function<WhiteListMapper, Function<List<WhiteListObject>, Boolean>> newWhiteListObjectFunction =