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

Complete HTTP alert (#2711)

* fix log error * Complete HTTP alert * Complete HTTP alert * fix comment * fix i81n * fix http test * formate code * formate code
parent 90c8b61d
......@@ -191,10 +191,10 @@ public class AlertInstanceController {
paramType = "body",
required = true,
dataTypeClass = AlertInstanceDTO.class)
public Result<Void> sendAlertMsgTest(@RequestBody AlertInstanceDTO alertInstanceDTO) {
public Result<String> sendAlertMsgTest(@RequestBody AlertInstanceDTO alertInstanceDTO) {
AlertResult alertResult = alertInstanceService.testAlert(alertInstanceDTO);
if (alertResult.getSuccess()) {
return Result.succeed(Status.SEND_TEST_SUCCESS);
return Result.succeed(alertResult.getMessage(), Status.SEND_TEST_SUCCESS);
} else {
return Result.failed(Status.SEND_TEST_FAILED);
}
......
......@@ -39,8 +39,8 @@ public class AlertBaseConstant {
public static final String AT_USERS = "atUsers";
public static final String PASSWORD = "password";
public static final String ALERT_TEMPLATE_TITLE = "Job Alert Test Title";
public static final String ALERT_TEMPLATE_MSG = "\n- **Job Name:** <font color='gray'>Test Job</font>\n"
public static final String ALERT_TEMPLATE_TITLE = "Dinky Job Alert Test Title";
public static final String ALERT_TEMPLATE_MSG = "\n- **Job Name:** <font color='gray'>Dinky Test Job</font>\n"
+ "- **Job Status:** <font color='red'>FAILED</font>\n"
+ "- **Alert Time:** 2023-01-01 12:00:00\n"
+ "- **Start Time:** 2023-01-01 12:00:00\n"
......
......@@ -22,18 +22,11 @@ package org.dinky.alert.http;
import org.dinky.alert.AbstractAlert;
import org.dinky.alert.AlertResult;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DingTalkAlert
* Http Alert
*
* @since 2022/2/23 19:28
*/
public class HttpAlert extends AbstractAlert {
private static final Logger log = LoggerFactory.getLogger(HttpAlert.class);
@Override
public String getType() {
......@@ -43,7 +36,6 @@ public class HttpAlert extends AbstractAlert {
@Override
public AlertResult send(String title, String content) {
HttpSender sender = new HttpSender(getConfig().getParam());
Map<String, Object> templateParams = sender.buildTemplateParams(title, content);
return sender.send(templateParams);
return sender.send(title, content);
}
}
......@@ -19,11 +19,9 @@
package org.dinky.alert.http;
/** DingTalkConstants */
/** Http Constants */
public class HttpConstants {
public static final String TYPE = "Http";
public static final String ALERT_TEMPLATE_TITLE = "title";
public static final String ALERT_TEMPLATE_CONTENT = "content";
public static final String REQUEST_TYPE_POST = "POST";
public static final String REQUEST_TYPE_GET = "GET";
......
......@@ -26,20 +26,15 @@ import org.dinky.data.ext.ConfigItem;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -47,17 +42,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
* DingTalkSender
* Http Sender
*/
public class HttpSender {
private static final Logger logger = LoggerFactory.getLogger(HttpSender.class);
private final HttpParams httpParams;
private HttpRequestBase httpRequest;
HttpSender(Map<String, Object> config) {
......@@ -65,35 +60,15 @@ public class HttpSender {
Asserts.checkNotNull(httpParams, "httpParams is null");
}
/**
* build template params
*
* @param title
* @param content
* @return
*/
public Map<String, Object> buildTemplateParams(String title, String content) {
Map<String, Object> params = new HashMap<>();
params.put(HttpConstants.ALERT_TEMPLATE_TITLE, title);
params.put(HttpConstants.ALERT_TEMPLATE_CONTENT, content);
return params;
}
/**
* send msg of main
*
* @param content: send msg content
* @return AlertResult
*/
public AlertResult send(Map<String, Object> templateParams) {
public AlertResult send(String title, String content) {
AlertResult alertResult = new AlertResult();
try {
createHttpRequest(templateParams);
} catch (MalformedURLException | URISyntaxException e) {
throw new RuntimeException(e);
}
if (httpParams.getMethod() == null) {
alertResult.setSuccess(false);
alertResult.setMessage("Request types are not supported");
......@@ -101,11 +76,12 @@ public class HttpSender {
}
try {
createHttpRequest(title, content);
String resp = this.getResponseString(httpRequest);
alertResult.setSuccess(true);
alertResult.setMessage(resp);
} catch (Exception e) {
logger.error("send http alert msg exception : {}", e.getMessage());
logger.error("send http alert msg failed", e);
alertResult.setSuccess(false);
alertResult.setMessage("send http request alert fail.");
}
......@@ -113,32 +89,22 @@ public class HttpSender {
return alertResult;
}
private void createHttpRequest(Map<String, Object> templateParams)
throws MalformedURLException, URISyntaxException {
private void createHttpRequest(String title, String content) {
if (HttpConstants.REQUEST_TYPE_POST.equals(httpParams.getMethod())) {
httpRequest = new HttpPost(httpParams.getUrl());
buildRequestHeader();
buildMsgToRequestBody(templateParams);
buildMsgToRequestBody(title, content);
} else if (HttpConstants.REQUEST_TYPE_GET.equals(httpParams.getMethod())) {
buildMsgToUrl(templateParams);
URL unencodeUrl = new URL(httpParams.getUrl());
URI uri = new URI(
unencodeUrl.getProtocol(),
unencodeUrl.getHost(),
unencodeUrl.getPath(),
unencodeUrl.getQuery(),
null);
httpRequest = new HttpGet(uri);
buildRequestHeader();
// TODO Get implementation
}
}
public String getResponseString(HttpRequestBase httpRequest) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, HttpConstants.DEFAULT_CHARSET);
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
CloseableHttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, HttpConstants.DEFAULT_CHARSET);
}
}
/**
......@@ -170,19 +136,19 @@ public class HttpSender {
/**
* set body params
*/
private void buildMsgToRequestBody(Map<String, Object> templateParams) {
private void buildMsgToRequestBody(String title, String content) {
try {
JSONObject jsonObject = JSONUtil.createObj();
templateParams.forEach(jsonObject::set);
if (CollUtil.isNotEmpty(httpParams.getBody())) {
httpParams.getBody().forEach(configItem -> {
jsonObject.set(configItem.getKey(), configItem.getValue());
});
JSONObject body = JSONUtil.parseObj(httpParams.getBody());
if (TextUtils.isEmpty(httpParams.getTitleFiled())) {
content = StrFormatter.format("{}\n{}", title, content);
} else {
body.putByPath(httpParams.getTitleFiled(), title);
}
StringEntity entity = new StringEntity(JSONUtil.toJsonStr(jsonObject), HttpConstants.DEFAULT_CHARSET);
body.putByPath(httpParams.getContentFiled(), content);
StringEntity entity = new StringEntity(JSONUtil.toJsonStr(body), HttpConstants.DEFAULT_CHARSET);
((HttpPost) httpRequest).setEntity(entity);
} catch (Exception e) {
logger.error("send http alert msg exception : {}", e.getMessage());
logger.error("send http alert msg exception", e);
}
}
}
......@@ -21,7 +21,6 @@ package org.dinky.alert.http.params;
import org.dinky.data.ext.ConfigItem;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
......@@ -35,8 +34,10 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
public class HttpParams {
private String url = "";
private String method = "";
private List<ConfigItem> headers = new ArrayList<>();
private List<ConfigItem> body = new ArrayList<>();
private String url;
private String method;
private String contentFiled;
private String titleFiled;
private List<ConfigItem> headers;
private String body;
}
......@@ -48,19 +48,12 @@ public class HttpSenderTest {
ConfigItem configItem = new ConfigItem("Content-Type", "application/json");
httpParams.setHeaders(Arrays.asList(configItem));
ConfigItem msgType = new ConfigItem("msgtype", "markdown");
ConfigItem title = new ConfigItem("title", AlertBaseConstant.ALERT_TEMPLATE_TITLE);
ConfigItem content = new ConfigItem("content", AlertBaseConstant.ALERT_TEMPLATE_MSG);
ConfigItem markdown = new ConfigItem("markdown", JSONUtil.toJsonStr(new HashMap<String, Object>() {
{
put("title", AlertBaseConstant.ALERT_TEMPLATE_TITLE);
put("text", AlertBaseConstant.ALERT_TEMPLATE_MSG);
}
}));
Arrays.asList(msgType, content, title, markdown).forEach(item -> {
httpParams.getBody().add(item);
});
httpParams.setBody(" {\n" + " \"msgtype\": \"markdown\",\n"
+ " \"markdown\": {\n"
+ " \"title\": \"http 测试\",\n"
+ " \"text\": \"\"\n"
+ " }\n"
+ "}");
httpConfig = JsonUtils.toMap(JSONUtil.toJsonStr(httpParams), String.class, Object.class);
}
......
......@@ -219,6 +219,15 @@
<include>dinky-alert-email-${project.version}.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.parent.basedir}/dinky-alert/dinky-alert-http/target
</directory>
<outputDirectory>lib</outputDirectory>
<includes>
<include>dinky-alert-http-${project.version}.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.parent.basedir}/dinky-alert/dinky-alert-feishu/target
</directory>
......
......@@ -79,6 +79,11 @@
<artifactId>dinky-alert-email</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-alert-http</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-metadata-mysql</artifactId>
......
......@@ -276,7 +276,11 @@ const FlinkDag = (props: DagProps) => {
{
key: '1',
label: 'Detail',
children: <div style={{whiteSpace:"pre"}}>{(currentSelect?.getData().description)?.replaceAll("<br/>","\n")}</div>
children: (
<div style={{ whiteSpace: 'pre' }}>
{currentSelect?.getData().description?.replaceAll('<br/>', '\n')}
</div>
)
},
{
key: '2',
......
......@@ -663,6 +663,12 @@ export default {
'rc.ai.http.methodPleaseHolder': 'Please select the request method',
'rc.ai.http.headers': 'Request headers',
'rc.ai.http.body': 'Request body',
'rc.ai.http.contentFiled': 'Content fields',
'rc.ai.http.contentFiled.help':
"In HTTP requests, the fields in the request body are replaced with 'Alarm Message', and if there are multiple layers of nested fields, use a JSON path expression, such as text.markdown.content",
'rc.ai.http.titleFiled': 'Title field',
'rc.ai.http.titleFiled.help':
"In HTTP requests, the field in the request body is replaced with 'header content', if there are multiple layers of nested fields, please use a JSON path expression, such as markdown.title, if not, the title is concatenated in the content field by default",
'rc.alert.template.create': 'Create Template',
'rc.alert.template.modify': 'Modify Template',
'rc.alert.template.new': 'Create an alert template',
......
......@@ -641,6 +641,12 @@ export default {
'rc.ai.http.methodPleaseHolder': '请选择请求方法',
'rc.ai.http.headers': '请求头',
'rc.ai.http.body': '请求体',
'rc.ai.http.contentFiled': '内容字段',
'rc.ai.http.contentFiled.help':
'在http请求中,请求体(body)内被替换为`告警消息`的字段,如果涉及多层嵌套字段,请使用json path表达式,例如 text.markdown.content',
'rc.ai.http.titleFiled': '标题字段',
'rc.ai.http.titleFiled.help':
'在http请求中,请求体(body)内被替换为`标题内容`的字段,如果涉及多层嵌套字段,请使用json path表达式,例如 markdown.title,如果不填写,则标题默认拼接在内容字段中',
'rc.alert.template.create': '创建模板',
'rc.alert.template.modify': '修改模板',
'rc.alert.template.new': '新建告警模板',
......
......@@ -20,7 +20,6 @@
import { TabsPageType, TaskDataType } from '@/pages/DataStudio/model';
import { JOB_LIFE_CYCLE, JOB_STATUS } from '@/pages/DevOps/constants';
import { DIALECT } from '@/services/constants';
import { EnvironmentOutlined } from '@ant-design/icons';
/**
* @description: 生成面包屑
......
......@@ -49,8 +49,10 @@ import {
import { JOB_LIFE_CYCLE, JOB_STATUS } from '@/pages/DevOps/constants';
import { SysConfigStateType } from '@/pages/SettingCenter/GlobalSetting/model';
import { SettingConfigKeyEnum } from '@/pages/SettingCenter/GlobalSetting/SettingOverView/constants';
import { queryList } from '@/services/api';
import { handleOption, handlePutDataJson, queryDataByParams } from '@/services/BusinessCrud';
import { DIALECT } from '@/services/constants';
import { API_CONSTANTS } from '@/services/endpoints';
import { DolphinTaskDefinition, DolphinTaskMinInfo } from '@/types/Studio/data.d';
import { l } from '@/utils/intl';
import { SuccessMessageAsync } from '@/utils/messages';
......@@ -71,8 +73,6 @@ import { connect } from '@umijs/max';
import { Breadcrumb, Descriptions, Modal, Space } from 'antd';
import { ButtonProps } from 'antd/es/button/button';
import React, { memo, useEffect, useState } from 'react';
import {queryList} from "@/services/api";
import {API_CONSTANTS} from "@/services/endpoints";
const headerStyle: React.CSSProperties = {
display: 'inline-flex',
......@@ -364,10 +364,10 @@ const HeaderContainer = (props: connect) => {
props: {
onClick: async () => {
const result = await queryList(API_CONSTANTS.GET_JOB_LIST, {
filter: {taskId: [currentData?.id]},
currentPage: 1,
filter: { taskId: [currentData?.id] },
currentPage: 1
});
window.open(`/#/devops/job-detail?id=${result.data[0].id}`)
window.open(`/#/devops/job-detail?id=${result.data[0].id}`);
},
target: '_blank'
}
......@@ -446,7 +446,12 @@ const HeaderContainer = (props: connect) => {
return (
<FlexCenterDiv style={{ width: (size.width - 2 * VIEW.paddingInline) / 2 }}>
{/*<Breadcrumb itemRender={(item, params, items, paths)=><span>{item.title}</span>} items={buildBreadcrumbItems(activeBreadcrumbTitle)} />*/}
<EnvironmentOutlined style={{paddingRight:20}}/><Breadcrumb style={{fontSize:12,lineHeight:VIEW.headerHeight+"px"}} separator={'/'} items={buildBreadcrumbItems(activeBreadcrumbTitle)} />
<EnvironmentOutlined style={{ paddingRight: 20 }} />
<Breadcrumb
style={{ fontSize: 12, lineHeight: VIEW.headerHeight + 'px' }}
separator={'/'}
items={buildBreadcrumbItems(activeBreadcrumbTitle)}
/>
</FlexCenterDiv>
);
};
......
......@@ -28,6 +28,7 @@ import {
SteamIcons,
UnknownIcons
} from '@/components/Icons/DevopsIcons';
import useHookRequest from '@/hooks/useHookRequest';
import { DevopContext } from '@/pages/DevOps';
import { JOB_STATUS } from '@/pages/DevOps/constants';
import StatisticsCard from '@/pages/DevOps/JobList/components/Overview/StatisticsCard';
......@@ -37,12 +38,11 @@ import { StatusCountOverView } from '@/types/Home/data';
import { l } from '@/utils/intl';
import { ProCard } from '@ant-design/pro-components';
import { Button, Col, Row, Space } from 'antd';
import { useContext, useEffect, useState } from 'react';
import useHookRequest from "@/hooks/useHookRequest";
import { useContext } from 'react';
const JobOverview = (props: any) => {
const { statusFilter, setStatusFilter } = useContext<any>(DevopContext);
const {data} = useHookRequest(getData,{defaultParams:[API_CONSTANTS.GET_STATUS_COUNT]})
const { data } = useHookRequest(getData, { defaultParams: [API_CONSTANTS.GET_STATUS_COUNT] });
const statusCount = data as StatusCountOverView;
return (
......
......@@ -17,17 +17,19 @@
*
*/
import CodeEdit from '@/components/CustomEditor/CodeEdit';
import { RequestMethod } from '@/pages/RegCenter/Alert/AlertInstance/constans';
import { Alert } from '@/types/RegCenter/data.d';
import { l } from '@/utils/intl';
import {
ProForm,
ProFormGroup,
ProFormItem,
ProFormList,
ProFormSelect,
ProFormText
} from '@ant-design/pro-components';
import { Space } from 'antd';
import { Col, Divider, Row, Space } from 'antd';
import { FormInstance } from 'antd/es/form/hooks/useForm';
import { Values } from 'async-validator';
import React from 'react';
......@@ -36,11 +38,15 @@ type HttpProps = {
values: Partial<Alert.AlertInstance>;
form: FormInstance<Values>;
};
const CodeEditProps = {
height: '30vh',
lineNumbers: 'on',
language: 'json'
};
const Http: React.FC<HttpProps> = (props) => {
const { values, form } = props;
const params = values.params as Alert.AlertInstanceParamsHttp;
return (
<>
<ProForm.Group>
......@@ -61,51 +67,55 @@ const Http: React.FC<HttpProps> = (props) => {
/>
</ProForm.Group>
{/*这有 bug,待解决*/}
<ProFormList
name={['params', 'headers']}
label={l('rc.ai.http.headers')}
copyIconProps={false}
required
initialValue={[{ key: '', value: '' }]}
deleteIconProps={{
tooltipText: l('rc.cc.deleteConfig')
}}
creatorButtonProps={{
style: { width: '100%' },
creatorButtonText: l('rc.cc.addConfig')
}}
>
<ProFormGroup key='headersGroup' style={{ width: '100%' }}>
<Space key={'config'} style={{ width: '100%' }} align='baseline'>
<ProFormText width={'md'} name='key' placeholder={l('rc.cc.key')} />
<ProFormText width={'lg'} name='value' placeholder={l('rc.cc.value')} />
</Space>
</ProFormGroup>
</ProFormList>
<Row>
<Col span={10}>
<ProFormList
name={['params', 'headers']}
label={l('rc.ai.http.headers')}
copyIconProps={false}
required
initialValue={[{ key: '', value: '' }]}
deleteIconProps={{
tooltipText: l('rc.cc.deleteConfig')
}}
creatorButtonProps={{
creatorButtonText: l('rc.cc.addConfig')
}}
>
<ProFormGroup key='headersGroup' style={{ width: '100%' }}>
<Space key={'config'}>
<ProFormText name='key' placeholder={l('rc.cc.key')} />
<ProFormText name='value' placeholder={l('rc.cc.value')} />
</Space>
</ProFormGroup>
</ProFormList>
{/*这有 bug,待解决*/}
<ProFormList
name={['params', 'body']}
label={l('rc.ai.http.body')}
copyIconProps={false}
required
initialValue={[{ key: '', value: '' }]}
deleteIconProps={{
tooltipText: l('rc.cc.deleteConfig')
}}
creatorButtonProps={{
style: { width: '100%' },
creatorButtonText: l('rc.cc.addConfig')
}}
>
<ProFormGroup key='bodyGroup' style={{ width: '100%' }}>
<Space key={'config'} style={{ width: '100%' }} align='baseline'>
<ProFormText width={'md'} name='key' placeholder={l('rc.cc.key')} />
<ProFormText width={'lg'} name='value' placeholder={l('rc.cc.value')} />
</Space>
</ProFormGroup>
</ProFormList>
<ProFormText
width='xl'
name={['params', 'contentFiled']}
label={l('rc.ai.http.contentFiled')}
required
tooltip={l('rc.ai.http.contentFiled.help')}
/>
<ProFormText
width='xl'
name={['params', 'titleFiled']}
label={l('rc.ai.http.titleFiled')}
tooltip={l('rc.ai.http.titleFiled.help')}
/>
</Col>
<Divider type={'vertical'} />
<Col span={12}>
<ProFormItem
required
key='httpBody'
name={['params', 'body']}
label={l('rc.ai.http.body')}
>
<CodeEdit {...CodeEditProps} code={params.body ?? ''} />
</ProFormItem>
</Col>
</Row>
</>
);
};
......
......@@ -37,9 +37,12 @@ export async function createOrModifyAlertInstance(alertInstance: Alert.AlertInst
export async function sendTest(alertInstance: Alert.AlertInstance) {
await LoadingMessageAsync(l('app.request.test.alert.msg'));
try {
const { code, msg } = await postAll(API_CONSTANTS.ALERT_INSTANCE_SEND_TEST, alertInstance);
const { data, code, msg } = await postAll(
API_CONSTANTS.ALERT_INSTANCE_SEND_TEST,
alertInstance
);
if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg);
SuccessMessage(`${msg}-->${data}`);
return true;
} else {
WarningMessage(msg);
......
......@@ -92,7 +92,7 @@ const FlinkK8s = (props: { type: string; value: any; form: FormInstance<Values>
reader.readAsText(file);
reader.onload = () => {
form.setFieldValue(name, reader.result as string);
onChange(reader.result as string + "\n");
onChange((reader.result as string) + '\n');
};
},
showUploadList: false
......
......@@ -65,6 +65,7 @@ declare namespace Alert {
url: string;
method: string;
headers: ConfigItem[];
body: any;
};
export type AlertInstanceParamsEmail = {
......
......@@ -560,6 +560,11 @@
<artifactId>dinky-alert-email</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-alert-http</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-daemon</artifactId>
......
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