Unverified Commit eecf7257 authored by gaoyan's avatar gaoyan Committed by GitHub

[ Optimization] Optimization the problem of repeated sending of alarms in multiple threads (#3033)

parent 2ae3943f
...@@ -21,6 +21,7 @@ package org.dinky.data.dto; ...@@ -21,6 +21,7 @@ package org.dinky.data.dto;
import org.dinky.data.annotations.ProcessId; import org.dinky.data.annotations.ProcessId;
import org.dinky.data.model.Task; import org.dinky.data.model.Task;
import org.dinky.data.model.alert.AlertGroup;
import org.dinky.data.model.ext.TaskExtConfig; import org.dinky.data.model.ext.TaskExtConfig;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
...@@ -127,6 +128,9 @@ public class TaskDTO extends AbstractStatementDTO { ...@@ -127,6 +128,9 @@ public class TaskDTO extends AbstractStatementDTO {
notes = "ID of the alert group associated with the task") notes = "ID of the alert group associated with the task")
private Integer alertGroupId; private Integer alertGroupId;
@ApiModelProperty(value = "Alert Group", dataType = "AlertGroup", notes = "Alert group associated with the task")
private AlertGroup alertGroup;
@ApiModelProperty(value = "Note", dataType = "String", notes = "Additional notes for the task") @ApiModelProperty(value = "Note", dataType = "String", notes = "Additional notes for the task")
private String note; private String note;
......
...@@ -21,7 +21,6 @@ package org.dinky.init; ...@@ -21,7 +21,6 @@ package org.dinky.init;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.constant.FlinkTaskConstant;
import org.dinky.daemon.pool.FlinkJobThreadPool; import org.dinky.daemon.pool.FlinkJobThreadPool;
import org.dinky.daemon.pool.ScheduleThreadPool; import org.dinky.daemon.pool.ScheduleThreadPool;
import org.dinky.daemon.task.DaemonTask; import org.dinky.daemon.task.DaemonTask;
...@@ -35,7 +34,6 @@ import org.dinky.data.model.rbac.Tenant; ...@@ -35,7 +34,6 @@ import org.dinky.data.model.rbac.Tenant;
import org.dinky.function.constant.PathConstant; import org.dinky.function.constant.PathConstant;
import org.dinky.function.pool.UdfCodePool; import org.dinky.function.pool.UdfCodePool;
import org.dinky.job.ClearJobHistoryTask; import org.dinky.job.ClearJobHistoryTask;
import org.dinky.job.DynamicResizeFlinkJobPoolTask;
import org.dinky.job.FlinkJobTask; import org.dinky.job.FlinkJobTask;
import org.dinky.job.SystemMetricsTask; import org.dinky.job.SystemMetricsTask;
import org.dinky.scheduler.client.ProjectClient; import org.dinky.scheduler.client.ProjectClient;
...@@ -162,10 +160,6 @@ public class SystemInit implements ApplicationRunner { ...@@ -162,10 +160,6 @@ public class SystemInit implements ApplicationRunner {
DaemonTask clearJobHistoryTask = DaemonTask.build(new DaemonTaskConfig(ClearJobHistoryTask.TYPE)); DaemonTask clearJobHistoryTask = DaemonTask.build(new DaemonTaskConfig(ClearJobHistoryTask.TYPE));
schedule.addSchedule(clearJobHistoryTask, new PeriodicTrigger(1, TimeUnit.HOURS)); schedule.addSchedule(clearJobHistoryTask, new PeriodicTrigger(1, TimeUnit.HOURS));
// Init flink job dynamic pool task
DaemonTask flinkJobPoolTask = DaemonTask.build(new DaemonTaskConfig(DynamicResizeFlinkJobPoolTask.TYPE));
schedule.addSchedule(flinkJobPoolTask, new PeriodicTrigger(FlinkTaskConstant.POLLING_GAP));
// Add flink running job task to flink job thread pool // Add flink running job task to flink job thread pool
List<JobInstance> jobInstances = jobInstanceService.listJobInstanceActive(); List<JobInstance> jobInstances = jobInstanceService.listJobInstanceActive();
FlinkJobThreadPool flinkJobThreadPool = FlinkJobThreadPool.getInstance(); FlinkJobThreadPool flinkJobThreadPool = FlinkJobThreadPool.getInstance();
......
/*
*
* 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.dinky.job;
import org.dinky.daemon.pool.FlinkJobThreadPool;
import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DynamicResizeFlinkJobPoolTask implements DaemonTask {
private DaemonTaskConfig config;
public static final String TYPE = DynamicResizeFlinkJobPoolTask.class.toString();
private final FlinkJobThreadPool defaultThreadPool = FlinkJobThreadPool.getInstance();
@Override
public boolean dealTask() {
int taskSize = defaultThreadPool.getTaskSize();
// Calculate the desired number of worker threads, adding one worker for every 100 tasks
int num = taskSize / 100 + 1;
// Dynamically adjust the number of worker threads in the thread pool
if (defaultThreadPool.getWorkCount() < num) {
defaultThreadPool.addWorkers(num - defaultThreadPool.getWorkCount());
} else if (defaultThreadPool.getWorkCount() > num) {
defaultThreadPool.removeWorker(defaultThreadPool.getWorkCount() - num);
}
return false;
}
@Override
public DaemonTask setConfig(DaemonTaskConfig config) {
this.config = config;
return this;
}
@Override
public DaemonTaskConfig getConfig() {
return config;
}
@Override
public String getType() {
return TYPE;
}
}
...@@ -31,25 +31,24 @@ import org.dinky.data.dto.TaskDTO; ...@@ -31,25 +31,24 @@ import org.dinky.data.dto.TaskDTO;
import org.dinky.data.enums.JobLifeCycle; import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.exception.DinkyException; import org.dinky.data.exception.DinkyException;
import org.dinky.data.model.Configuration;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.alert.AlertGroup; import org.dinky.data.model.alert.AlertGroup;
import org.dinky.data.model.alert.AlertHistory; import org.dinky.data.model.alert.AlertHistory;
import org.dinky.data.model.alert.AlertInstance; import org.dinky.data.model.alert.AlertInstance;
import org.dinky.data.model.ext.JobAlertData; import org.dinky.data.model.ext.JobAlertData;
import org.dinky.data.model.ext.JobInfoDetail; import org.dinky.data.model.ext.JobInfoDetail;
import org.dinky.data.options.JobAlertRuleOptions; import org.dinky.data.options.JobAlertRuleOptions;
import org.dinky.service.AlertGroupService;
import org.dinky.service.AlertHistoryService; import org.dinky.service.AlertHistoryService;
import org.dinky.service.SysConfigService;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.service.impl.AlertRuleServiceImpl; import org.dinky.service.impl.AlertRuleServiceImpl;
import org.dinky.service.impl.SysConfigServiceImpl;
import org.dinky.utils.JsonUtils; import org.dinky.utils.JsonUtils;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.jeasy.rules.api.Facts; import org.jeasy.rules.api.Facts;
...@@ -61,14 +60,13 @@ import org.jeasy.rules.core.RuleBuilder; ...@@ -61,14 +60,13 @@ import org.jeasy.rules.core.RuleBuilder;
import org.jeasy.rules.spel.SpELCondition; import org.jeasy.rules.spel.SpELCondition;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import freemarker.template.TemplateException;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -77,10 +75,9 @@ import lombok.extern.slf4j.Slf4j; ...@@ -77,10 +75,9 @@ import lombok.extern.slf4j.Slf4j;
public class JobAlertHandler { public class JobAlertHandler {
private static final AlertHistoryService alertHistoryService; private static final AlertHistoryService alertHistoryService;
private static final AlertGroupService alertGroupService;
private static final TaskService taskService; private static final TaskService taskService;
private static final SysConfigService sysConfigService;
private static final AlertRuleServiceImpl alertRuleService; private static final AlertRuleServiceImpl alertRuleService;
private static final SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
/** /**
* Rules for evaluating alert conditions. * Rules for evaluating alert conditions.
...@@ -97,14 +94,30 @@ public class JobAlertHandler { ...@@ -97,14 +94,30 @@ public class JobAlertHandler {
*/ */
private FreeMarkerHolder freeMarkerHolder; private FreeMarkerHolder freeMarkerHolder;
/**
* 缓存告警发送记录,用于防止单位时间内频繁发送重复告警 key为任务实例id,
* value为告警发送记录map,key为告警id,value为触发次数 |
* Cache alert sending records to prevent frequent sending of duplicate alerts within a unit time.
* The key is the task instance ID, the value is the alert sending record map,
* the key is the alert ID, and the value is the number of triggers
*/
private static LoadingCache<Integer, Map<Integer, Integer>> alertCache;
private static volatile JobAlertHandler defaultJobAlertHandler; private static volatile JobAlertHandler defaultJobAlertHandler;
static { static {
taskService = SpringContextUtils.getBean("taskServiceImpl", TaskService.class); taskService = SpringContextUtils.getBean("taskServiceImpl", TaskService.class);
alertHistoryService = SpringContextUtils.getBean("alertHistoryServiceImpl", AlertHistoryService.class); alertHistoryService = SpringContextUtils.getBean("alertHistoryServiceImpl", AlertHistoryService.class);
alertGroupService = SpringContextUtils.getBean("alertGroupServiceImpl", AlertGroupService.class);
alertRuleService = SpringContextUtils.getBean("alertRuleServiceImpl", AlertRuleServiceImpl.class); alertRuleService = SpringContextUtils.getBean("alertRuleServiceImpl", AlertRuleServiceImpl.class);
sysConfigService = SpringContextUtils.getBean("sysConfigServiceImpl", SysConfigServiceImpl.class);
Configuration<Integer> jobReSendDiffSecond = systemConfiguration.getJobReSendDiffSecond();
jobReSendDiffSecond.addChangeEvent((c) -> {
alertCache = CacheBuilder.newBuilder()
// 与expireAfterAccess不同,写入后定时过期 | Different from expireAfterAccess, it expires after writing
.expireAfterWrite(c, TimeUnit.SECONDS)
.build(CacheLoader.from(() -> new HashMap<>()));
});
jobReSendDiffSecond.runChangeEvent();
} }
public static JobAlertHandler getInstance() { public static JobAlertHandler getInstance() {
...@@ -186,102 +199,42 @@ public class JobAlertHandler { ...@@ -186,102 +199,42 @@ public class JobAlertHandler {
* @param facts The facts representing the job details. * @param facts The facts representing the job details.
* @param alertRuleDTO Alert Rule Info. * @param alertRuleDTO Alert Rule Info.
*/ */
private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) { private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) throws Exception {
TaskDTO task = taskService.getTaskInfoById(facts.get(JobAlertRuleOptions.FIELD_TASK_ID)); int jobInstanceId = facts.get(JobAlertRuleOptions.FIELD_JOB_INSTANCE_ID);
int taskId = facts.get(JobAlertRuleOptions.FIELD_TASK_ID);
// 进行是否需要告警判断 | Determine whether an alert is required
Map<Integer, Integer> map = alertCache.get(jobInstanceId);
Integer ruleId = alertRuleDTO.getId();
if (!map.containsKey(ruleId)) {
// 初始化触发次数 | Initialize the number of triggers
map.put(ruleId, 1);
}
// 触发次数+1 | Trigger count +1
Integer maxSendCount = systemConfiguration.getDiffMinuteMaxSendCount().getValue();
// 判断是否超过最大发送次数,超过则不再发送,等待缓存过期 | Determine whether the maximum number of sends has been exceeded,
if (map.get(ruleId) > maxSendCount) {
return;
}
map.put(ruleId, map.get(ruleId) + 1);
TaskDTO task = taskService.getTaskInfoById(taskId);
if (!Objects.equals(task.getStep(), JobLifeCycle.PUBLISH.getValue())) { if (!Objects.equals(task.getStep(), JobLifeCycle.PUBLISH.getValue())) {
// Only publish job can be alerted // Only publish job can be alerted
return; return;
} }
Map<String, Object> dataModel = new HashMap<>(facts.asMap()); Map<String, Object> dataModel = new HashMap<>(facts.asMap());
dataModel.put(JobAlertRuleOptions.OPTIONS_JOB_ALERT_RULE, alertRuleDTO); dataModel.put(JobAlertRuleOptions.OPTIONS_JOB_ALERT_RULE, alertRuleDTO);
String alertContent; String alertContent = freeMarkerHolder.buildWithData(alertRuleDTO.getTemplateName(), dataModel);
try {
alertContent = freeMarkerHolder.buildWithData(alertRuleDTO.getTemplateName(), dataModel);
} catch (IOException | TemplateException e) {
log.error("Alert Error: ", e);
return;
}
if (!Asserts.isNull(task.getAlertGroupId())) { if (!Asserts.isNull(task.getAlertGroup())) {
AlertGroup alertGroup = alertGroupService.getAlertGroupInfo(task.getAlertGroupId()); AlertGroup alertGroup = task.getAlertGroup();
if (Asserts.isNotNull(alertGroup)) { alertGroup.getInstances().stream()
for (AlertInstance alertInstance : alertGroup.getInstances()) { .filter(Objects::nonNull)
if (alertInstance == null || !alertInstance.getEnabled()) { .filter(AlertInstance::getEnabled)
continue; .forEach(alertInstance -> sendAlert(
} alertInstance, jobInstanceId, alertGroup.getId(), alertRuleDTO.getName(), alertContent));
// if current time in diff minute time, and alert send record count > diff minute max send count,
// then not send, else send
// todo: 多线程会重复发送,需要优化
if (isGTEMaxSendRecordCount(alertGroup, task) && timeIsInDiffMinute(alertGroup, task)) {
sendAlert(
alertInstance,
facts.get(JobAlertRuleOptions.FIELD_JOB_INSTANCE_ID),
alertGroup.getId(),
alertRuleDTO.getName(),
alertContent);
}
}
}
}
}
/**
* 判断是否大于最大发送次数 | Whether it is greater than the maximum number of sending times
*
* @param alertGroup
* @param task
* @return if true, then send alert
*/
private boolean isGTEMaxSendRecordCount(AlertGroup alertGroup, TaskDTO task) {
// check diff seconds max send count| 指定时间间隔内最大发送次数 2
int diffMinuteMaxSendCount = (int) sysConfigService
.getOneConfigByKey(Status.SYS_ENV_SETTINGS_DIFF_MINUTE_MAX_SEND_COUNT.getKey())
.getValue();
// check diff seconds max send count | 指定时间间隔 1
int jobResendDiffSecond = (int) sysConfigService
.getOneConfigByKey(Status.SYS_ENV_SETTINGS_JOB_RESEND_DIFF_SECOND.getKey())
.getValue();
// 获取当前时间 - 指定时间间隔 = 指定时间间隔前的时间 | get current time - diff seconds = diff seconds time
DateTime diffMinuteTime = DateUtil.offsetSecond(DateUtil.date(), -jobResendDiffSecond);
// 获取指定时间间隔前的时间到当前时间之间的发送记录数 | get diff minute time to current time alert send record count
long jobInstanceAlertSendRecordCount = alertHistoryService.count(
new LambdaQueryWrapper<>(AlertHistory.class)
.eq(AlertHistory::getAlertGroupId, alertGroup.getId()) // alert group id
.eq(AlertHistory::getJobInstanceId, task.getJobInstanceId()) // assert group id
.ge(true, AlertHistory::getCreateTime, diffMinuteTime) // 指定时间间隔前的时间 | diff minute time
.le(true, AlertHistory::getCreateTime, DateUtil.date()) // 当前时间 | current time
);
// 1. 如果 当前时间 在 指定时间间隔前的时间区间内,且发送记录数大于指定时间间隔内最大发送次数,则不发送 | if current time in diff minute time, and alert send
// record count > diff minute max send count, then not send
// 2. 如果 当前时间 不在 指定时间间隔前的时间区间内,则发送 | if current time not in diff minute time, then send
if (jobInstanceAlertSendRecordCount >= diffMinuteMaxSendCount) {
log.warn(
Status.JOB_ALERT_MAX_SEND_COUNT.getMessage(),
jobResendDiffSecond,
diffMinuteMaxSendCount,
jobInstanceAlertSendRecordCount);
return false;
} }
return true;
}
/**
* 判断当前时间是否在指定时间间隔前的时间区间内 | Whether the current time is in the time interval before the specified time interval
*
* @param alertGroup
* @param task
* @return
*/
private boolean timeIsInDiffMinute(AlertGroup alertGroup, TaskDTO task) {
// check diff minute max send count | 指定时间间隔 1
int jobResendDiffSecond = (int) sysConfigService
.getOneConfigByKey(Status.SYS_ENV_SETTINGS_JOB_RESEND_DIFF_SECOND.getKey())
.getValue();
// 获取当前时间 - 指定时间间隔 = 指定时间间隔前的时间 | get current time - diff seconds = diff seconds time
DateTime diffSecondTime = DateUtil.offsetSecond(DateUtil.date(), -jobResendDiffSecond);
// 1. 如果 当前时间 在 指定时间间隔前的时间区间内
return !DateUtil.date().before(diffSecondTime);
} }
/** /**
......
...@@ -530,6 +530,10 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -530,6 +530,10 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
taskDTO.setStatus(jobInstance.getStatus()); taskDTO.setStatus(jobInstance.getStatus());
} }
} }
if (!Asserts.isNull(taskDTO.getAlertGroupId())) {
AlertGroup alertGroup = alertGroupService.getAlertGroupInfo(taskDTO.getAlertGroupId());
taskDTO.setAlertGroup(alertGroup);
}
return taskDTO; return taskDTO;
} }
...@@ -547,16 +551,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -547,16 +551,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
TaskDTO task = getTaskInfoById(taskId); TaskDTO task = getTaskInfoById(taskId);
task.setStep(lifeCycle.getValue()); task.setStep(lifeCycle.getValue());
if (lifeCycle == JobLifeCycle.PUBLISH) { if (lifeCycle == JobLifeCycle.PUBLISH) {
// List<SqlExplainResult> sqlExplainResults = explainTask(task);
// for (SqlExplainResult sqlExplainResult : sqlExplainResults) {
// if (!sqlExplainResult.isParseTrue() || !sqlExplainResult.isExplainTrue()) {
// throw new SqlExplainExcepition(StrFormatter.format(
// "task [{}] sql explain failed, sql [{}], error: [{}]",
// task.getName(),
// sqlExplainResult.getSql(),
// sqlExplainResult.getError()));
// }
// }
Integer taskVersionId = taskVersionService.createTaskVersionSnapshot(task); Integer taskVersionId = taskVersionService.createTaskVersionSnapshot(task);
task.setVersionId(taskVersionId); task.setVersionId(taskVersionId);
} }
...@@ -570,7 +564,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -570,7 +564,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
log.warn( log.warn(
"JobInstance [{}] step change to [{}] ,Trigger Force Refresh", "JobInstance [{}] step change to [{}] ,Trigger Force Refresh",
jobInstance.getName(), jobInstance.getName(),
lifeCycle.getValue()); lifeCycle.name());
} }
} }
return saved; return saved;
......
org.dinky.job.FlinkJobTask org.dinky.job.FlinkJobTask
org.dinky.job.DynamicResizeFlinkJobPoolTask
org.dinky.job.SystemMetricsTask org.dinky.job.SystemMetricsTask
org.dinky.job.ClearJobHistoryTask org.dinky.job.ClearJobHistoryTask
\ No newline at end of file
...@@ -81,7 +81,7 @@ public class HttpUtils { ...@@ -81,7 +81,7 @@ public class HttpUtils {
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) { if (statusCode == HttpStatus.SC_OK) {
logger.info( logger.debug(
"post data success, return http status code: {} , msg: {}", "post data success, return http status code: {} , msg: {}",
statusCode, statusCode,
response.getStatusLine().getReasonPhrase()); response.getStatusLine().getReasonPhrase());
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.daemon.entity; package org.dinky.daemon.entity;
import org.dinky.daemon.pool.FlinkJobThreadPool;
import org.dinky.daemon.task.DaemonTask; import org.dinky.daemon.task.DaemonTask;
import lombok.Data; import lombok.Data;
...@@ -55,7 +56,7 @@ public class TaskWorker implements Runnable { ...@@ -55,7 +56,7 @@ public class TaskWorker implements Runnable {
try { try {
boolean done = daemonTask.dealTask(); boolean done = daemonTask.dealTask();
if (done) { if (done) {
queue.removeByTask(daemonTask); FlinkJobThreadPool.getInstance().removeByTaskConfig(daemonTask.getConfig());
} }
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
......
...@@ -35,15 +35,15 @@ import java.util.concurrent.atomic.AtomicInteger; ...@@ -35,15 +35,15 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public class FlinkJobThreadPool implements ThreadPool { public class FlinkJobThreadPool implements ThreadPool {
private static final int MAX_WORKER_NUM = 10; private static final int MAX_WORKER_NUM = 20;
private static final int DEFAULT_WORKER_NUM = 5; private static final int DEFAULT_WORKER_NUM = 1;
private static final int MIN_WORKER_NUM = 1; private static final int MIN_WORKER_NUM = 1;
private final List<TaskWorker> workers = Collections.synchronizedList(new ArrayList<>()); private final List<TaskWorker> workers = Collections.synchronizedList(new ArrayList<>());
private final Object lock = new Object(); private final Object lock = new Object();
private volatile AtomicInteger workerNum = new AtomicInteger(0); private final AtomicInteger workerNum = new AtomicInteger(0);
private final TaskQueue<DaemonTask> queue = new TaskQueue<>(); private final TaskQueue<DaemonTask> queue = new TaskQueue<>();
...@@ -63,6 +63,28 @@ public class FlinkJobThreadPool implements ThreadPool { ...@@ -63,6 +63,28 @@ public class FlinkJobThreadPool implements ThreadPool {
public void execute(DaemonTask daemonTask) { public void execute(DaemonTask daemonTask) {
if (daemonTask != null) { if (daemonTask != null) {
queue.addTask(daemonTask); queue.addTask(daemonTask);
resizeWorkers(queue.getTaskSize() / 10);
}
}
public DaemonTask removeByTaskConfig(DaemonTaskConfig daemonTask) {
DaemonTask removed = queue.removeByTaskConfig(daemonTask);
resizeWorkers(queue.getTaskSize() / 10);
return removed;
}
private void resizeWorkers(int afterNum) {
synchronized (lock) {
int workerNum = this.workerNum.get();
afterNum = Math.min(afterNum, MAX_WORKER_NUM);
afterNum = Math.max(afterNum, MIN_WORKER_NUM);
if (afterNum > workerNum) {
addWorkers(afterNum - workerNum);
} else if (afterNum < workerNum) {
removeWorker(workerNum - afterNum);
}
} }
} }
...@@ -126,10 +148,6 @@ public class FlinkJobThreadPool implements ThreadPool { ...@@ -126,10 +148,6 @@ public class FlinkJobThreadPool implements ThreadPool {
return queue.getByTaskConfig(daemonTask); return queue.getByTaskConfig(daemonTask);
} }
public DaemonTask removeByTaskConfig(DaemonTaskConfig daemonTask) {
return queue.removeByTaskConfig(daemonTask);
}
public int getWorkCount() { public int getWorkCount() {
synchronized (lock) { synchronized (lock) {
return this.workerNum.get(); return this.workerNum.get();
......
...@@ -56,7 +56,7 @@ export const BOOLEAN_VALUE_ENUM: DefaultOptionType[] = [ ...@@ -56,7 +56,7 @@ export const BOOLEAN_VALUE_ENUM: DefaultOptionType[] = [
]; ];
export const AlertRules: any = { export const AlertRules: any = {
jobName: { taskId: {
label: l('sys.alert.rule.label.taskId'), label: l('sys.alert.rule.label.taskId'),
valueType: OperatorType.NUMBER_VALUE valueType: OperatorType.NUMBER_VALUE
}, },
......
...@@ -120,6 +120,7 @@ const RuleEditForm = (props: AlertRuleFormProps) => { ...@@ -120,6 +120,7 @@ const RuleEditForm = (props: AlertRuleFormProps) => {
> >
<ProFormGroup> <ProFormGroup>
<ProFormText name='id' hidden={true} /> <ProFormText name='id' hidden={true} />
<ProFormText name='ruleType' hidden={true} />
<ProFormText <ProFormText
disabled={isSystem} disabled={isSystem}
rules={[{ required: true }]} rules={[{ required: true }]}
......
...@@ -60,6 +60,9 @@ const AlertRuleList: React.FC = () => { ...@@ -60,6 +60,9 @@ const AlertRuleList: React.FC = () => {
setRuleState(InitAlertRuleState); setRuleState(InitAlertRuleState);
}; };
async function handleSubmit(rule: AlertRule) { async function handleSubmit(rule: AlertRule) {
if (rule.ruleType != RuleType.SYSTEM) {
rule.ruleType = RuleType.CUSTOM;
}
await executeAndCallbackRefresh(() => handleAddOrUpdate(API_CONSTANTS.ALERT_RULE, rule)); await executeAndCallbackRefresh(() => handleAddOrUpdate(API_CONSTANTS.ALERT_RULE, rule));
handleCleanState(); handleCleanState();
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment