Unverified Commit 4dc9984e authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

modify alert rule layout (#2313)

* modify alert rule layout * added some constants * fix code style * fix code style * fix code style * fix code style
parent a377b709
......@@ -37,6 +37,7 @@ import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobInstance;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Task;
import org.dinky.data.options.AlertRuleOptions;
import org.dinky.job.FlinkJobTaskPool;
import org.dinky.service.impl.AlertGroupServiceImpl;
import org.dinky.service.impl.AlertHistoryServiceImpl;
......@@ -129,8 +130,8 @@ public class JobAlerts extends BaseSchedule {
*/
@PostConstruct
public void init() {
refeshRulesData();
addSchedule("JobAlert", this::check, new PeriodicTrigger(1000 * 30));
refreshRulesData();
addSchedule(AlertRuleOptions.JOB_ALERT_SCHEDULE, this::check, new PeriodicTrigger(1000 * 30));
}
/**
......@@ -142,20 +143,26 @@ public class JobAlerts extends BaseSchedule {
for (Map.Entry<String, JobInfoDetail> job : taskPool.entrySet()) {
JobInfoDetail jobInfoDetail = job.getValue();
String key = job.getKey();
ruleFacts.put("time", TimeUtil.nowStr());
ruleFacts.put("jobDetail", jobInfoDetail);
ruleFacts.put("job", jobInfoDetail.getJobHistory().getJob());
ruleFacts.put("key", key);
ruleFacts.put("jobInstance", jobInfoDetail.getInstance());
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_TIME, TimeUtil.nowStr());
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_JOB_DETAIL, jobInfoDetail);
ruleFacts.put(
"startTime",
AlertRuleOptions.JOB_ALERT_RULE_JOB_NAME,
jobInfoDetail.getJobHistory().getJob());
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_KEY, key);
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_JOB_INSTANCE, jobInfoDetail.getInstance());
ruleFacts.put(
AlertRuleOptions.JOB_ALERT_RULE_START_TIME,
TimeUtil.convertTimeToString(jobInfoDetail.getHistory().getStartTime()));
ruleFacts.put(
"endTime",
AlertRuleOptions.JOB_ALERT_RULE_END_TIME,
TimeUtil.convertTimeToString(jobInfoDetail.getHistory().getEndTime()));
ruleFacts.put("checkPoints", jobInfoDetail.getJobHistory().getCheckpoints());
ruleFacts.put("cluster", jobInfoDetail.getCluster());
ruleFacts.put("exceptions", jobInfoDetail.getJobHistory().getExceptions());
ruleFacts.put(
AlertRuleOptions.JOB_ALERT_RULE_CHECK_POINTS,
jobInfoDetail.getJobHistory().getCheckpoints());
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_CLUSTER, jobInfoDetail.getCluster());
ruleFacts.put(
AlertRuleOptions.JOB_ALERT_RULE_EXCEPTIONS,
jobInfoDetail.getJobHistory().getExceptions());
rulesEngine.fire(rules, ruleFacts);
}
}
......@@ -163,9 +170,9 @@ public class JobAlerts extends BaseSchedule {
/**
* Refreshes the alert rules and related data.
*/
public void refeshRulesData() {
ruleFacts.put("exceptionRule", new ExceptionRule());
ruleFacts.put("checkpointRule", new CheckpointsRule());
public void refreshRulesData() {
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_REFRESH_RULES_DATA, new ExceptionRule());
ruleFacts.put(AlertRuleOptions.JOB_ALERT_RULE_CHECKPOINT_RULES, new CheckpointsRule());
List<AlertRuleDTO> ruleDTOS = alertRuleService.getBaseMapper().selectWithTemplate();
freeMarkerHolder = new FreeMarkerHolder();
......@@ -212,7 +219,7 @@ public class JobAlerts extends BaseSchedule {
* @param alertRuleDTO Alert Rule Info.
*/
private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) {
JobInfoDetail jobInfoDetail = facts.get("jobDetail");
JobInfoDetail jobInfoDetail = facts.get(AlertRuleOptions.JOB_ALERT_RULE_JOB_DETAIL);
JobInstance jobInstance = jobInfoDetail.getInstance();
Task task = taskService.getById(jobInfoDetail.getInstance().getTaskId());
......@@ -221,9 +228,9 @@ public class JobAlerts extends BaseSchedule {
SystemConfiguration.getInstances().getDinkyAddr(),
task.getId());
Map<String, Object> dataModel = new HashMap<>(facts.asMap());
dataModel.put("task", task);
dataModel.put("taskUrl", taskUrl);
dataModel.put("rule", alertRuleDTO);
dataModel.put(AlertRuleOptions.JOB_ALERT_RULE_TASK, task);
dataModel.put(AlertRuleOptions.JOB_ALERT_RULE_TASK_URL, taskUrl);
dataModel.put(AlertRuleOptions.JOB_ALERT_RULE, alertRuleDTO);
String alertContent;
......
......@@ -34,10 +34,12 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiImplicitParam;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
......@@ -61,16 +63,35 @@ public class AlertRuleController {
}
@PutMapping
public Result<Boolean> put(@RequestBody AlertRule alertRule) {
@ApiImplicitParam(
name = "alertRule",
value = "alertRule",
required = true,
dataType = "AlertRule",
paramType = "body",
dataTypeClass = AlertRule.class)
public Result<Boolean> saveOrUpdateAlertRule(@RequestBody AlertRule alertRule) {
boolean saved = alertRuleService.saveOrUpdate(alertRule);
if (saved) {
jobAlerts.refeshRulesData();
jobAlerts.refreshRulesData();
return Result.succeed(Status.MODIFY_SUCCESS);
}
return Result.succeed(saved);
return Result.failed(Status.MODIFY_FAILED);
}
@DeleteMapping
public Result<Boolean> delete(int id) {
return Result.succeed(alertRuleService.removeById(id));
@ApiImplicitParam(
name = "id",
value = "id",
required = true,
dataType = "Integer",
paramType = "query",
dataTypeClass = Integer.class,
example = "1")
public Result<Boolean> deleteAlertRuleById(@RequestParam Integer id) {
if (alertRuleService.removeById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
}
return Result.failed(Status.DELETE_FAILED);
}
}
......@@ -33,8 +33,10 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.ApiImplicitParam;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
......@@ -50,14 +52,31 @@ public class AlertTemplateConteroller {
}
@DeleteMapping
@Log(title = "Delete AlertTemplate ", businessType = BusinessType.INSERT_OR_UPDATE)
public Result<Boolean> delete(int id) {
return Result.succeed(alertTemplateService.removeById(id));
@Log(title = "Delete AlertTemplate ", businessType = BusinessType.DELETE)
@ApiImplicitParam(
name = "id",
value = "AlertTemplate ID",
required = true,
dataType = "Integer",
paramType = "query",
example = "1")
public Result<Boolean> deleteAlertTemplateById(@RequestParam Integer id) {
if (alertTemplateService.removeById(id)) {
return Result.succeed(Status.DELETE_SUCCESS);
}
return Result.failed(Status.DELETE_FAILED);
}
@PutMapping
@Log(title = "Insert OR Update AlertTemplate ", businessType = BusinessType.INSERT_OR_UPDATE)
public Result<Void> put(@RequestBody AlertTemplate alertTemplate) {
@ApiImplicitParam(
name = "alertTemplate",
value = "AlertTemplate",
required = true,
dataType = "AlertTemplate",
paramType = "body",
dataTypeClass = AlertTemplate.class)
public Result<Void> saveOrUpdateAlertTemplate(@RequestBody AlertTemplate alertTemplate) {
if (alertTemplateService.saveOrUpdate(alertTemplate)) {
return Result.succeed(Status.SAVE_SUCCESS);
} else {
......
......@@ -23,6 +23,8 @@ import org.dinky.mybatis.model.SuperEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
......@@ -31,11 +33,31 @@ import lombok.NoArgsConstructor;
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("dinky_alert_rules")
@ApiModel(value = "AlertRule", description = "AlertRule")
public class AlertRule extends SuperEntity {
@ApiModelProperty(value = "rule", required = true, dataType = "String", example = "rule")
String rule;
@ApiModelProperty(value = "templateId", required = true, dataType = "int", example = "1")
int templateId;
@ApiModelProperty(
value = "ruleType",
required = true,
dataType = "String",
example = "ruleType",
allowableValues = "CUSTOM,SYSTEM")
String ruleType;
@ApiModelProperty(
value = "triggerConditions",
required = true,
dataType = "String",
example = "or",
allowableValues = "or,and")
String triggerConditions;
@ApiModelProperty(value = "description", required = true, dataType = "String", example = "description")
String description;
}
......@@ -23,12 +23,16 @@ import org.dinky.mybatis.model.SuperEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("dinky_alert_template")
@ApiModel(value = "AlertTemplate", description = "AlertTemplate")
public class AlertTemplate extends SuperEntity {
@ApiModelProperty(value = "name", required = true, dataType = "String", example = "# 11 \n > 11")
String templateContent;
}
/*
*
* 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.data.options;
public class AlertRuleOptions {
public static final String JOB_ALERT_SCHEDULE = "JobAlert";
public static final String JOB_ALERT_RULE_TIME = "time";
public static final String JOB_ALERT_RULE_JOB_DETAIL = "jobDetail";
public static final String JOB_ALERT_RULE_JOB_NAME = "job";
public static final String JOB_ALERT_RULE_KEY = "key";
public static final String JOB_ALERT_RULE_JOB_INSTANCE = "jobInstance";
public static final String JOB_ALERT_RULE_START_TIME = "startTime";
public static final String JOB_ALERT_RULE_END_TIME = "endTime";
public static final String JOB_ALERT_RULE_CHECK_POINTS = "checkPoints";
public static final String JOB_ALERT_RULE_CLUSTER = "cluster";
public static final String JOB_ALERT_RULE_EXCEPTIONS = "exceptions";
public static final String JOB_ALERT_RULE_REFRESH_RULES_DATA = "refreshRulesData";
public static final String JOB_ALERT_RULE_CHECKPOINT_RULES = "checkpointRule";
public static final String JOB_ALERT_RULE_TASK = "task";
public static final String JOB_ALERT_RULE_TASK_URL = "taskUrl";
public static final String JOB_ALERT_RULE = "rule";
}
......@@ -24,6 +24,9 @@ import org.dinky.alert.AlertResult;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.TemplateException;
/**
......@@ -32,6 +35,7 @@ import freemarker.template.TemplateException;
* @since 2022/2/23 19:28
*/
public class DingTalkAlert extends AbstractAlert {
private static final Logger log = LoggerFactory.getLogger(DingTalkAlert.class);
@Override
public String getType() {
......@@ -45,6 +49,7 @@ public class DingTalkAlert extends AbstractAlert {
String built = buildContent(sender.buildTemplateParams(title, content));
return sender.send(built);
} catch (TemplateException | IOException e) {
log.error("{}'message send error, Reason:{}", getType(), e.getMessage());
throw new RuntimeException(e);
}
}
......
......@@ -24,4 +24,10 @@ import org.dinky.alert.AlertBaseConstant;
/** DingTalkConstants */
public class DingTalkConstants extends AlertBaseConstant {
public static final String TYPE = "DingTalk";
public static final String ALERT_TEMPLATE_TITLE = "title";
public static final String ALERT_TEMPLATE_CONTENT = "content";
public static final String ALERT_TEMPLATE_KEYWORD = "keyword";
public static final String ALERT_TEMPLATE_AT_MOBILE = "atMobile";
public static final String ALERT_TEMPLATE_AT_MOBILES = "atMobiles";
public static final String ALERT_TEMPLATE_AT_ALL = "atAll";
}
......@@ -43,7 +43,6 @@ import org.slf4j.LoggerFactory;
*
*/
public class DingTalkSender {
private static final Logger logger = LoggerFactory.getLogger(DingTalkSender.class);
private final String url;
private final String keyword;
......@@ -80,13 +79,13 @@ public class DingTalkSender {
*/
public Map<String, Object> buildTemplateParams(String title, String content) {
Map<String, Object> params = new HashMap<>();
params.put("title", title);
params.put("content", content);
params.put("keyword", keyword);
params.put(DingTalkConstants.ALERT_TEMPLATE_TITLE, title);
params.put(DingTalkConstants.ALERT_TEMPLATE_CONTENT, content);
params.put(DingTalkConstants.ALERT_TEMPLATE_KEYWORD, keyword);
String[] atMobile = Asserts.isNullString(atMobiles) ? new String[] {} : atMobiles.split(",");
params.put("atMobile", atMobile);
params.put("atMobiles", atMobiles);
params.put("atAll", atAll.toString());
params.put(DingTalkConstants.ALERT_TEMPLATE_AT_MOBILE, atMobile);
params.put(DingTalkConstants.ALERT_TEMPLATE_AT_MOBILES, atMobiles);
params.put(DingTalkConstants.ALERT_TEMPLATE_AT_ALL, atAll.toString());
return params;
}
......
......@@ -29,11 +29,14 @@ import java.util.Map;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.TemplateException;
/** EmailAlert */
public class EmailAlert extends AbstractAlert {
private static final Logger log = LoggerFactory.getLogger(EmailAlert.class);
@Override
public String getType() {
......@@ -44,13 +47,14 @@ public class EmailAlert extends AbstractAlert {
public AlertResult send(String title, String content) {
Map<String, Object> params = new HashMap<>();
params.put("title", title);
params.put("content", markdownToHtml(content));
params.put(EmailConstants.ALERT_TEMPLATE_TITLE, title);
params.put(EmailConstants.ALERT_TEMPLATE_CONTENT, markdownToHtml(content));
EmailSender emailSender = new EmailSender(getConfig().getParam());
try {
return emailSender.send(title, buildContent(params));
} catch (TemplateException | IOException e) {
log.error("{}'message send error, Reason:{}", getType(), e.getMessage());
throw new RuntimeException(e);
}
}
......
......@@ -53,4 +53,6 @@ public class EmailConstants extends AlertBaseConstant {
public static final String XLS_FILE_PATH = "xls.file.path";
public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
public static final String XLS_FILE_DEFAULT_PATH = "/tmp/xls";
public static final String ALERT_TEMPLATE_TITLE = "title";
public static final String ALERT_TEMPLATE_CONTENT = "content";
}
......@@ -31,7 +31,6 @@ import freemarker.template.TemplateException;
/** FeiShuAlert */
public class FeiShuAlert extends AbstractAlert {
private static final Logger logger = LoggerFactory.getLogger(FeiShuAlert.class);
@Override
......@@ -47,6 +46,7 @@ public class FeiShuAlert extends AbstractAlert {
logger.info("Send FeiShu alert title: {}", title);
return sender.send(built);
} catch (TemplateException | IOException e) {
logger.error("{}'message send error, Reason:{}", getType(), e.getMessage());
throw new RuntimeException(e);
}
}
......
......@@ -24,7 +24,10 @@ import org.dinky.alert.AlertBaseConstant;
/** FeiShuConstants */
public class FeiShuConstants extends AlertBaseConstant {
public static final String TYPE = "FeiShu";
public static final String SIGN_TMESTAMP = "timestamp";
public static final String SIGN = "sign";
public static final String ALERT_TEMPLATE_TITLE = "title";
public static final String ALERT_TEMPLATE_CONTENT = "content";
public static final String ALERT_TEMPLATE_KEYWORD = "keyword";
public static final String ALERT_TEMPLATE_AT_USERS = "atUsers";
}
......@@ -43,7 +43,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* fei shu sender
*/
public final class FeiShuSender {
private static final Logger logger = LoggerFactory.getLogger(FeiShuSender.class);
private final String url;
private final String secret;
......@@ -82,16 +81,16 @@ public final class FeiShuSender {
*/
public Map<String, Object> buildTemplateParams(String title, String content) {
Map<String, Object> params = new HashMap<>();
params.put("title", title);
params.put("content", content);
params.put("keyword", keyword);
params.put(FeiShuConstants.ALERT_TEMPLATE_TITLE, title);
params.put(FeiShuConstants.ALERT_TEMPLATE_CONTENT, content);
params.put(FeiShuConstants.ALERT_TEMPLATE_KEYWORD, keyword);
if (Asserts.isNotNullString(secret)) {
Integer currentTimeMillis = Math.toIntExact(System.currentTimeMillis() / 1000);
params.put(FeiShuConstants.SIGN_TMESTAMP, currentTimeMillis);
params.put(FeiShuConstants.SIGN, getSign(secret, currentTimeMillis));
}
String[] atUsers = Asserts.isNullString(atUserIds) ? new String[] {"all"} : atUserIds.split(",");
params.put("atUsers", atUsers);
params.put(FeiShuConstants.ALERT_TEMPLATE_AT_USERS, atUsers);
return params;
}
......
......@@ -39,7 +39,6 @@ import cn.hutool.json.JSONUtil;
/** SmsSender todo: https://wind.kim/doc/start/springboot.html */
public class SmsSender {
private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);
private static SupplierConfig configLoader = null;
private static BaseProviderFactory providerFactory = null;
......
......@@ -24,6 +24,9 @@ import org.dinky.alert.AlertResult;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.StrFormatter;
import freemarker.template.TemplateException;
......@@ -34,6 +37,7 @@ import freemarker.template.TemplateException;
* @since 2022/2/23 21:09
*/
public class WeChatAlert extends AbstractAlert {
private static final Logger logger = LoggerFactory.getLogger(WeChatAlert.class);
@Override
public String getType() {
......@@ -54,6 +58,7 @@ public class WeChatAlert extends AbstractAlert {
String built = buildContent(sender.buildTemplateParams(title, content));
return sender.send(built);
} catch (TemplateException | IOException e) {
logger.error("{}'message send error, Reason:{}", getType(), e.getMessage());
throw new RuntimeException(e);
}
}
......
......@@ -30,10 +30,14 @@ public class WeChatConstants extends AlertBaseConstant {
public static final String WECHAT_TOKEN_URL =
"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={secret}";
public static final String CORP_ID = "corpId";
public static final String TEAM_SEND_MSG = "teamSendMsg";
public static final String AGENT_ID = "agentId";
public static final String SEND_TYPE = "sendType";
public static final String ACCESS_TOKEN = "access_token";
public static final String ALERT_TEMPLATE_TITLE = "title";
public static final String ALERT_TEMPLATE_CONTENT = "content";
public static final String ALERT_TEMPLATE_AGENT_ID = "agentId";
public static final String ALERT_TEMPLATE_AT_USERS = "atUsers";
}
......@@ -51,7 +51,6 @@ import cn.hutool.core.text.StrFormatter;
* @since 2022/2/23 21:11
*/
public class WeChatSender {
private static final Logger logger = LoggerFactory.getLogger(WeChatSender.class);
private static final String CORP_ID_REGEX = "{corpId}";
private static final String SECRET_REGEX = "{secret}";
......@@ -94,13 +93,13 @@ public class WeChatSender {
*/
public Map<String, Object> buildTemplateParams(String title, String content) {
Map<String, Object> params = new HashMap<>();
params.put("title", title);
params.put("content", content);
params.put("agentId", weChatAgentId);
params.put(WeChatConstants.ALERT_TEMPLATE_TITLE, title);
params.put(WeChatConstants.ALERT_TEMPLATE_CONTENT, content);
params.put(WeChatConstants.ALERT_TEMPLATE_AGENT_ID, weChatAgentId);
List<String> atUsers = Arrays.stream(weChatUsers.split(","))
.map(u -> StrFormatter.format("<@{}>", u))
.collect(Collectors.toList());
params.put("atUsers", atUsers);
params.put(WeChatConstants.ALERT_TEMPLATE_AT_USERS, atUsers);
return params;
}
......@@ -117,7 +116,7 @@ public class WeChatSender {
}
return checkWeChatSendMsgResult(HttpUtils.post(url, content));
} catch (Exception e) {
logger.info("send we chat alert msg exception : {}", e.getMessage());
logger.error("send we chat alert msg exception : {}", e.getMessage());
alertResult.setMessage("send we chat alert fail");
alertResult.setSuccess(false);
}
......@@ -142,7 +141,7 @@ public class WeChatSender {
}
}
} catch (IOException e) {
logger.info("we chat alert get token error{}", e.getMessage());
logger.error("we chat alert get token error{}", e.getMessage());
}
return null;
}
......@@ -152,13 +151,13 @@ public class WeChatSender {
alertResult.setSuccess(false);
if (null == result) {
alertResult.setMessage("we chat send fail");
logger.info("send we chat msg error,resp is null");
logger.error("send we chat msg error,resp is null");
return alertResult;
}
AlertSendResponse sendMsgResponse = JSONUtil.parseObject(result, AlertSendResponse.class);
if (null == sendMsgResponse) {
alertResult.setMessage("we chat send fail");
logger.info("send we chat msg error,resp error");
logger.error("send we chat msg error,resp error");
return alertResult;
}
if (sendMsgResponse.getErrcode() == 0) {
......
......@@ -5,7 +5,7 @@
"license": "Apache License 2.0",
"scripts": {
"analyze": "cross-env ANALYZE=1 max build",
"build": "concurrently max build && npm run build-to-admin --prefix ../dinky-web-flink",
"build": "max build && npm install --prefix ../dinky-web-flink && npm run build-to-admin --prefix ../dinky-web-flink",
"deploy": "npm run build && npm run gh-pages",
"dev": "npm run build-to-admin --prefix ../dinky-web-flink && npm run start:dev ",
"postinstall": "max setup",
......
......@@ -958,16 +958,17 @@ export default {
'sys.alert.rule.rule': 'Rule',
'sys.alert.rule.ruleType': 'Rule Type',
'sys.alert.rule.template': 'Alert Template',
'sys.alert.rule.triger': 'Trigger Configuration',
'sys.alert.rule.trigerConditions': 'Trigger Conditions',
'sys.alert.rule.trigger': 'Trigger Configuration',
'sys.alert.rule.triggerConditions': 'Trigger Conditions',
'sys.alert.rule.anyRule': 'Any Rule',
'sys.alert.rule.allRule': 'All Rules',
'sys.alert.rule.trigerRule': 'Trigger Rule',
'sys.alert.rule.triggerRule': 'Trigger Rule',
'sys.alert.rule.addRule': 'Add Rule',
'sys.alert.rule.jobStatus': 'Job Status',
'sys.alert.rule.checkpointTime': 'Checkpoint Time',
'sys.alert.rule.checkpointFailed': 'Checkpoint Failed',
'sys.alert.rule.jobException': 'Job Exception',
'sys.alert.rule.delete': 'Are you sure you want to delete this alert rule?',
// metrics
// server
......
......@@ -932,16 +932,17 @@ export default {
'sys.alert.rule.ruleType': '规则类型',
'sys.alert.rule.rule': '规则',
'sys.alert.rule.template': '告警模板',
'sys.alert.rule.triger': '触发配置',
'sys.alert.rule.trigerConditions': '触发条件',
'sys.alert.rule.trigger': '触发配置',
'sys.alert.rule.triggerConditions': '触发条件',
'sys.alert.rule.anyRule': '任意规则',
'sys.alert.rule.allRule': '所有规则',
'sys.alert.rule.trigerRule': '触发规则',
'sys.alert.rule.triggerRule': '触发规则',
'sys.alert.rule.addRule': '添加规则',
'sys.alert.rule.jobStatus': '作业状态',
'sys.alert.rule.checkpointTime': 'CheckPoint时间',
'sys.alert.rule.checkpointFailed': 'Checkpoint失败',
'sys.alert.rule.jobException': '作业产生异常',
'sys.alert.rule.delete': '你确定要删除该告警策略吗?',
// metrics
// server
......
......@@ -17,8 +17,14 @@
*
*/
import { RuleType } from '@/pages/SettingCenter/AlertRule/constants';
import {
AlertRules,
RuleOperator,
RuleType,
TriggerType
} from '@/pages/SettingCenter/AlertRule/constants';
import { getData } from '@/services/api';
import { SWITCH_OPTIONS } from '@/services/constants';
import { API_CONSTANTS } from '@/services/endpoints';
import { Alert } from '@/types/RegCenter/data';
import { AlertRule } from '@/types/SettingCenter/data';
......@@ -85,42 +91,45 @@ const RuleEditForm = (props: AlertRuleFormProps) => {
}}
initialValues={values}
>
<ProFormText name='id' hidden={true} />
<ProFormText
disabled={isSystem}
rules={[{ required: true }]}
name='name'
width='md'
label={l('sys.alert.rule.name')}
placeholder={l('sys.alert.rule.name')}
/>
<ProFormSelect
label={l('sys.alert.rule.template')}
width='md'
name='templateId'
request={async () => getAlertTemplate()}
placeholder={l('sys.alert.rule.template')}
rules={[{ required: true, message: l('sys.alert.rule.template') }]}
/>
<ProFormTextArea width='md' name='description' label={l('global.table.note')} />
<Divider orientation={'left'}>{l('sys.alert.rule.triger')}</Divider>
<ProFormGroup>
<ProFormText name='id' hidden={true} />
<ProFormText
disabled={isSystem}
rules={[{ required: true }]}
name='name'
width='md'
label={l('sys.alert.rule.name')}
placeholder={l('sys.alert.rule.name')}
/>
<ProFormSelect
label={l('sys.alert.rule.template')}
width='md'
name='templateId'
request={async () => getAlertTemplate()}
placeholder={l('sys.alert.rule.template')}
rules={[{ required: true, message: l('sys.alert.rule.template') }]}
/>
</ProFormGroup>
<ProFormGroup>
<ProFormTextArea width='md' name='description' label={l('global.table.note')} />
<ProFormSwitch name='enabled' {...SWITCH_OPTIONS()} label={l('global.table.isEnable')} />
</ProFormGroup>
<Divider orientation={'left'}>{l('sys.alert.rule.trigger')}</Divider>
<ProFormRadio.Group
disabled={isSystem}
name='triggerConditions'
label={l('sys.alert.rule.trigerConditions')}
options={[
{ label: l('sys.alert.rule.anyRule'), value: ' or ' },
{ label: l('sys.alert.rule.allRule'), value: ' and ' }
]}
label={l('sys.alert.rule.triggerConditions')}
rules={[{ required: true }]}
options={TriggerType}
/>
<ProFormList
name='rule'
label={l('sys.alert.rule.trigerRule')}
label={l('sys.alert.rule.triggerRule')}
creatorButtonProps={
isSystem
? false
......@@ -150,34 +159,13 @@ const RuleEditForm = (props: AlertRuleFormProps) => {
name='ruleKey'
width={'sm'}
mode={'single'}
options={[
{ label: l('sys.alert.rule.jobStatus'), value: 'jobInstance.status' },
{
label: l('sys.alert.rule.checkpointTime'),
value: 'checkPoints.checkpointTime(#key,#checkPoints)'
},
{
label: l('sys.alert.rule.checkpointFailed'),
value: 'checkPoints.checkFailed(#key,#checkPoints)'
},
{
label: l('sys.alert.rule.jobException'),
value: 'exceptionRule.isException(#key,#exceptions)'
}
]}
options={AlertRules}
/>
<ProFormSelect
disabled={isSystem}
name='ruleOperator'
mode={'single'}
options={[
{ label: '>', value: 'GT' },
{ label: '<', value: 'LT' },
{ label: '=', value: 'EQ' },
{ label: '>=', value: 'GE' },
{ label: '<=', value: 'LE' },
{ label: '!=', value: 'NE' }
]}
options={RuleOperator}
/>
<ProFormText
......@@ -188,8 +176,6 @@ const RuleEditForm = (props: AlertRuleFormProps) => {
</Space>
</ProFormGroup>
</ProFormList>
<ProFormSwitch name='enabled' label={l('button.enable')} />
</DrawerForm>
);
};
......
......@@ -37,26 +37,27 @@ const AlertRuleList: React.FC = () => {
const [ruleState, setRuleState] = useState<AlertRuleListState>(InitAlertRuleState);
const actionRef = useRef<ActionType>(); // table action
const editClick = (item: AlertRule) => {
setRuleState((prevState) => ({
...prevState,
editOpen: !prevState.editOpen,
value: item
}));
const executeAndCallbackRefresh = async (callback: () => void) => {
setRuleState((prevState) => ({ ...prevState, loading: true }));
await callback();
setRuleState((prevState) => ({ ...prevState, loading: false }));
actionRef.current?.reload?.();
};
const editClick = async (item: AlertRule) => {
await executeAndCallbackRefresh(() =>
setRuleState((prevState) => ({
...prevState,
editOpen: !prevState.editOpen,
value: item
}))
);
};
const handleCleanState = () => {
setRuleState((prevState) => ({
...prevState,
value: {},
addedOpen: false,
editOpen: false
}));
setRuleState(InitAlertRuleState);
};
async function handleSubmit(rule: AlertRule) {
await handleAddOrUpdate(API_CONSTANTS.ALERT_RULE, rule);
actionRef.current?.reload?.();
await executeAndCallbackRefresh(() => handleAddOrUpdate(API_CONSTANTS.ALERT_RULE, rule));
handleCleanState();
}
......@@ -82,6 +83,14 @@ const AlertRuleList: React.FC = () => {
title: l('sys.alert.rule.name'),
dataIndex: 'name'
},
{
title: l('sys.alert.rule.triggerConditions'),
dataIndex: 'triggerConditions',
valueEnum: {
' or ': l('sys.alert.rule.anyRule'),
' and ': l('sys.alert.rule.allRule')
}
},
{
title: l('sys.alert.rule.ruleType'),
dataIndex: 'ruleType'
......@@ -95,10 +104,10 @@ const AlertRuleList: React.FC = () => {
<EnableSwitchBtn
key={`${record.id}_enable`}
record={record}
onChange={() => {
onChange={async () => {
record.enabled = !record.enabled;
record.rule = JSON.stringify(record.rule);
handleSubmit(record);
await handleSubmit(record);
}}
/>
);
......@@ -126,7 +135,7 @@ const AlertRuleList: React.FC = () => {
<PopconfirmDeleteBtn
key={`${record.id}_delete`}
onClick={async () => await handleRemoveById(API_CONSTANTS.ALERT_RULE, record.id)}
description={l('user.status')}
description={l('sys.alert.rule.delete')}
/>
)
]
......@@ -138,6 +147,7 @@ const AlertRuleList: React.FC = () => {
<ProTable<AlertRule>
actionRef={actionRef}
headerTitle={false}
loading={ruleState.loading}
{...PROTABLE_OPTIONS_PUBLIC}
toolBarRender={() => [
<CreateBtn
......
......@@ -15,7 +15,38 @@
* limitations under the License.
*/
import { l } from '@/utils/intl';
import { CheckboxOptionType } from 'antd/es/checkbox/Group';
import { DefaultOptionType } from 'antd/es/select';
export enum RuleType {
SYSTEM = 'SYSTEM',
CUSTOM = 'CUSTOM'
}
export const TriggerType: CheckboxOptionType[] = [
{ label: l('sys.alert.rule.anyRule'), value: ' or ' },
{ label: l('sys.alert.rule.allRule'), value: ' and ' }
];
export const AlertRules: DefaultOptionType[] = [
{ label: l('sys.alert.rule.jobStatus'), value: 'jobInstance.status' },
{
label: l('sys.alert.rule.checkpointTime'),
value: 'checkPoints.checkpointTime(#key,#checkPoints)'
},
{
label: l('sys.alert.rule.checkpointFailed'),
value: 'checkPoints.checkFailed(#key,#checkPoints)'
},
{ label: l('sys.alert.rule.jobException'), value: 'exceptionRule.isException(#key,#exceptions)' }
];
export const RuleOperator: DefaultOptionType[] = [
{ label: '>', value: 'GT' },
{ label: '<', value: 'LT' },
{ label: '=', value: 'EQ' },
{ label: '!=', value: 'NE' },
{ label: '>=', value: 'GE' },
{ label: '<=', value: 'LE' }
];
export const validationOptions = (value: string) => {
switch (value) {
case 'jobInstance.status':
case 'checkPoints.checkFailed(#key,#checkPoints)':
case 'exceptionRule.isException(#key,#exceptions)':
return true;
case 'checkPoints.checkpointTime(#key,#checkPoints)':
return false;
default:
return false;
}
};
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