mavenRemoteRepository) {
- this.mavenRemoteRepository = mavenRemoteRepository;
- return this;
- }
-
- public DolphinPluginManagerConfig setMavenRemoteRepository(String mavenRemoteRepository) {
- this.mavenRemoteRepository = ImmutableList.copyOf(Splitter.on(',').omitEmptyStrings().trimResults().split(mavenRemoteRepository));
- return this;
- }
-}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPlugin.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPlugin.java
new file mode 100644
index 0000000000..5bbc21930f
--- /dev/null
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPlugin.java
@@ -0,0 +1,147 @@
+/*
+ * 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.apache.dolphinscheduler.alert.plugin;
+
+import org.apache.dolphinscheduler.alert.manager.DingTalkManager;
+import org.apache.dolphinscheduler.alert.manager.EmailManager;
+import org.apache.dolphinscheduler.alert.manager.EnterpriseWeChatManager;
+import org.apache.dolphinscheduler.alert.utils.Constants;
+import org.apache.dolphinscheduler.alert.utils.DingTalkUtils;
+import org.apache.dolphinscheduler.alert.utils.EnterpriseWeChatUtils;
+import org.apache.dolphinscheduler.common.utils.CollectionUtils;
+import org.apache.dolphinscheduler.common.utils.StringUtils;
+import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
+import org.apache.dolphinscheduler.plugin.model.AlertData;
+import org.apache.dolphinscheduler.plugin.model.AlertInfo;
+import org.apache.dolphinscheduler.plugin.model.PluginName;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * EmailAlertPlugin
+ *
+ * This plugin is a default plugin, and mix up email and enterprise wechat, because adapt with former alert behavior
+ */
+public class EmailAlertPlugin implements AlertPlugin {
+
+ private static final Logger logger = LoggerFactory.getLogger(EmailAlertPlugin.class);
+
+ private PluginName pluginName;
+
+ private static final EmailManager emailManager = new EmailManager();
+ private static final EnterpriseWeChatManager weChatManager = new EnterpriseWeChatManager();
+ private static final DingTalkManager dingTalkManager = new DingTalkManager();
+
+ public EmailAlertPlugin() {
+ this.pluginName = new PluginName();
+ this.pluginName.setEnglish(Constants.PLUGIN_DEFAULT_EMAIL_EN);
+ this.pluginName.setChinese(Constants.PLUGIN_DEFAULT_EMAIL_CH);
+ }
+
+ @Override
+ public String getId() {
+ return Constants.PLUGIN_DEFAULT_EMAIL_ID;
+ }
+
+ @Override
+ public PluginName getName() {
+ return pluginName;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Map process(AlertInfo info) {
+ Map retMaps = new HashMap<>();
+
+ AlertData alert = info.getAlertData();
+
+ List receiversList = (List) info.getProp(Constants.PLUGIN_DEFAULT_EMAIL_RECEIVERS);
+
+ // receiving group list
+ // custom receiver
+ String receivers = alert.getReceivers();
+ if (StringUtils.isNotEmpty(receivers)) {
+ String[] splits = receivers.split(",");
+ receiversList.addAll(Arrays.asList(splits));
+ }
+
+ List receiversCcList = new ArrayList<>();
+ // Custom Copier
+ String receiversCc = alert.getReceiversCc();
+ if (StringUtils.isNotEmpty(receiversCc)) {
+ String[] splits = receiversCc.split(",");
+ receiversCcList.addAll(Arrays.asList(splits));
+ }
+
+ if (CollectionUtils.isEmpty(receiversList) && CollectionUtils.isEmpty(receiversCcList)) {
+ logger.warn("alert send error : At least one receiver address required");
+ retMaps.put(Constants.STATUS, "false");
+ retMaps.put(Constants.MESSAGE, "execution failure,At least one receiver address required.");
+ return retMaps;
+ }
+
+ retMaps = emailManager.send(receiversList, receiversCcList, alert.getTitle(), alert.getContent(),
+ alert.getShowType());
+
+ //send flag
+ boolean flag = false;
+
+ if (retMaps == null) {
+ retMaps = new HashMap<>();
+ retMaps.put(Constants.MESSAGE, "alert send error.");
+ retMaps.put(Constants.STATUS, "false");
+ logger.info("alert send error : {}", retMaps.get(Constants.MESSAGE));
+ return retMaps;
+ }
+
+ flag = Boolean.parseBoolean(String.valueOf(retMaps.get(Constants.STATUS)));
+
+ if (flag) {
+ logger.info("alert send success");
+ retMaps.put(Constants.MESSAGE, "email send success.");
+ if (EnterpriseWeChatUtils.isEnable()) {
+ logger.info("Enterprise WeChat is enable!");
+ try {
+ String token = EnterpriseWeChatUtils.getToken();
+ weChatManager.send(info, token);
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ }
+ }
+
+ if (DingTalkUtils.IS_ENABLE_DING_TALK) {
+ logger.info("Ding Talk is enable.");
+ dingTalkManager.send(info);
+ }
+
+ } else {
+ retMaps.put(Constants.MESSAGE, "alert send error.");
+ logger.info("alert send error : {}", retMaps.get(Constants.MESSAGE));
+ }
+
+ return retMaps;
+ }
+
+}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessor.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessor.java
deleted file mode 100644
index 5e8a8f89d6..0000000000
--- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessor.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert.processor;
-
-import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
-import org.apache.dolphinscheduler.alert.runner.AlertSender;
-import org.apache.dolphinscheduler.common.utils.Preconditions;
-import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.PluginDao;
-import org.apache.dolphinscheduler.remote.command.Command;
-import org.apache.dolphinscheduler.remote.command.CommandType;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendRequestCommand;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseCommand;
-import org.apache.dolphinscheduler.remote.processor.NettyRequestProcessor;
-import org.apache.dolphinscheduler.remote.utils.JsonSerializer;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import io.netty.channel.Channel;
-
-/**
- * alert request processor
- */
-public class AlertRequestProcessor implements NettyRequestProcessor {
-
- private final Logger logger = LoggerFactory.getLogger(AlertRequestProcessor.class);
- private AlertDao alertDao;
- private PluginDao pluginDao;
- private AlertPluginManager alertPluginManager;
-
- public AlertRequestProcessor(AlertDao alertDao, AlertPluginManager alertPluginManager, PluginDao pluginDao) {
- this.alertDao = alertDao;
- this.pluginDao = pluginDao;
- this.alertPluginManager = alertPluginManager;
- }
-
- @Override
- public void process(Channel channel, Command command) {
- Preconditions.checkArgument(CommandType.ALERT_SEND_REQUEST == command.getType(),
- String.format("invalid command type : %s", command.getType()));
-
- AlertSendRequestCommand alertSendRequestCommand = JsonSerializer.deserialize(
- command.getBody(), AlertSendRequestCommand.class);
- logger.info("received command : {}", alertSendRequestCommand);
-
- AlertSender alertSender = new AlertSender(alertDao, alertPluginManager, pluginDao);
- AlertSendResponseCommand alertSendResponseCommand = alertSender.syncHandler(alertSendRequestCommand.getGroupId(), alertSendRequestCommand.getTitle(), alertSendRequestCommand.getContent());
- channel.writeAndFlush(alertSendResponseCommand.convert2Command(command.getOpaque()));
-
- }
-}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/runner/AlertSender.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/runner/AlertSender.java
index d635574543..1bae9c7724 100644
--- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/runner/AlertSender.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/runner/AlertSender.java
@@ -14,28 +14,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.alert.runner;
-import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
+import org.apache.dolphinscheduler.alert.utils.Constants;
import org.apache.dolphinscheduler.common.enums.AlertStatus;
-import org.apache.dolphinscheduler.common.utils.CollectionUtils;
+import org.apache.dolphinscheduler.common.plugin.PluginManager;
import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.PluginDao;
import org.apache.dolphinscheduler.dao.entity.Alert;
-import org.apache.dolphinscheduler.dao.entity.AlertPluginInstance;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseCommand;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseResult;
-import org.apache.dolphinscheduler.spi.alert.AlertChannel;
-import org.apache.dolphinscheduler.spi.alert.AlertData;
-import org.apache.dolphinscheduler.spi.alert.AlertInfo;
-import org.apache.dolphinscheduler.spi.alert.AlertResult;
+import org.apache.dolphinscheduler.dao.entity.User;
+import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
+import org.apache.dolphinscheduler.plugin.model.AlertData;
+import org.apache.dolphinscheduler.plugin.model.AlertInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.Map;
/**
* alert sender
@@ -46,135 +41,60 @@ public class AlertSender {
private List alertList;
private AlertDao alertDao;
- private PluginDao pluginDao;
- private AlertPluginManager alertPluginManager;
+ private PluginManager pluginManager;
- public AlertSender(AlertPluginManager alertPluginManager) {
- this.alertPluginManager = alertPluginManager;
+ public AlertSender() {
}
- public AlertSender(AlertDao alertDao, AlertPluginManager alertPluginManager, PluginDao pluginDao) {
- super();
- this.alertDao = alertDao;
- this.pluginDao = pluginDao;
- this.alertPluginManager = alertPluginManager;
- }
-
- public AlertSender(List alertList, AlertDao alertDao, AlertPluginManager alertPluginManager, PluginDao pluginDao) {
+ public AlertSender(List alertList, AlertDao alertDao, PluginManager pluginManager) {
super();
this.alertList = alertList;
this.alertDao = alertDao;
- this.pluginDao = pluginDao;
- this.alertPluginManager = alertPluginManager;
+ this.pluginManager = pluginManager;
}
public void run() {
+ List users;
+ Map retMaps = null;
for (Alert alert : alertList) {
- //get alert group from alert
- int alertGroupId = alert.getAlertGroupId();
- List alertInstanceList = alertDao.listInstanceByAlertGroupId(alertGroupId);
- if (CollectionUtils.isEmpty(alertInstanceList)) {
- logger.error("send alert msg fail,no bind plugin instance.");
- return;
+ users = alertDao.listUserByAlertgroupId(alert.getAlertGroupId());
+
+ // receiving group list
+ List receiversList = new ArrayList<>();
+ for (User user : users) {
+ receiversList.add(user.getEmail());
}
+
AlertData alertData = new AlertData();
alertData.setId(alert.getId())
- .setContent(alert.getContent())
- .setLog(alert.getLog())
- .setTitle(alert.getTitle());
-
- for (AlertPluginInstance instance : alertInstanceList) {
-
- AlertResult alertResult = this.alertResultHandler(instance, alertData);
- AlertStatus alertStatus = Boolean.parseBoolean(String.valueOf(alertResult.getStatus())) ? AlertStatus.EXECUTION_SUCCESS : AlertStatus.EXECUTION_FAILURE;
- alertDao.updateAlert(alertStatus, alertResult.getMessage(), alert.getId());
-
+ .setAlertGroupId(alert.getAlertGroupId())
+ .setContent(alert.getContent())
+ .setLog(alert.getLog())
+ .setReceivers(alert.getReceivers())
+ .setReceiversCc(alert.getReceiversCc())
+ .setShowType(alert.getShowType().getDescp())
+ .setTitle(alert.getTitle());
+
+ AlertInfo alertInfo = new AlertInfo();
+ alertInfo.setAlertData(alertData);
+
+ alertInfo.addProp("receivers", receiversList);
+
+ AlertPlugin emailPlugin = pluginManager.findOne(Constants.PLUGIN_DEFAULT_EMAIL_ID);
+ retMaps = emailPlugin.process(alertInfo);
+
+ if (retMaps == null) {
+ alertDao.updateAlert(AlertStatus.EXECUTION_FAILURE, "alert send error", alert.getId());
+ logger.error("alert send error : return value is null");
+ } else if (!Boolean.parseBoolean(String.valueOf(retMaps.get(Constants.STATUS)))) {
+ alertDao.updateAlert(AlertStatus.EXECUTION_FAILURE, String.valueOf(retMaps.get(Constants.MESSAGE)), alert.getId());
+ logger.error("alert send error : {}", retMaps.get(Constants.MESSAGE));
+ } else {
+ alertDao.updateAlert(AlertStatus.EXECUTION_SUCCESS, (String) retMaps.get(Constants.MESSAGE), alert.getId());
+ logger.info("alert send success");
}
}
}
- /**
- * sync send alert handler
- *
- * @param alertGroupId alertGroupId
- * @param title title
- * @param content content
- * @return AlertSendResponseCommand
- */
- public AlertSendResponseCommand syncHandler(int alertGroupId, String title, String content) {
-
- List alertInstanceList = alertDao.listInstanceByAlertGroupId(alertGroupId);
- AlertData alertData = new AlertData();
- alertData.setContent(title)
- .setTitle(content);
-
- boolean sendResponseStatus = true;
- List sendResponseResults = new ArrayList<>();
-
- if (CollectionUtils.isEmpty(alertInstanceList)) {
- sendResponseStatus = false;
- AlertSendResponseResult alertSendResponseResult = new AlertSendResponseResult();
- String message = String.format("Alert GroupId %s send error : not found alert instance", alertGroupId);
- alertSendResponseResult.setStatus(sendResponseStatus);
- alertSendResponseResult.setMessage(message);
- sendResponseResults.add(alertSendResponseResult);
- logger.error("Alert GroupId {} send error : not found alert instance", alertGroupId);
- return new AlertSendResponseCommand(sendResponseStatus, sendResponseResults);
- }
-
- for (AlertPluginInstance instance : alertInstanceList) {
- AlertResult alertResult = this.alertResultHandler(instance, alertData);
- AlertSendResponseResult alertSendResponseResult = new AlertSendResponseResult(
- Boolean.parseBoolean(String.valueOf(alertResult.getStatus())), alertResult.getMessage());
- sendResponseStatus = sendResponseStatus && alertSendResponseResult.getStatus();
- sendResponseResults.add(alertSendResponseResult);
- }
-
- return new AlertSendResponseCommand(sendResponseStatus, sendResponseResults);
- }
-
- /**
- * alert result handler
- *
- * @param instance instance
- * @param alertData alertData
- * @return AlertResult
- */
- private AlertResult alertResultHandler(AlertPluginInstance instance, AlertData alertData) {
- String pluginName = pluginDao.getPluginDefineById(instance.getPluginDefineId()).getPluginName();
- AlertChannel alertChannel = alertPluginManager.getAlertChannelMap().get(pluginName);
- AlertResult alertResultExtend = new AlertResult();
- String pluginInstanceName = instance.getInstanceName();
- if (alertChannel == null) {
- String message = String.format("Alert Plugin %s send error : return value is null", pluginInstanceName);
- alertResultExtend.setStatus(String.valueOf(false));
- alertResultExtend.setMessage(message);
- logger.error("Alert Plugin {} send error : not found plugin {}", pluginInstanceName, pluginName);
- return alertResultExtend;
- }
-
- AlertInfo alertInfo = new AlertInfo();
- alertInfo.setAlertData(alertData);
- alertInfo.setAlertParams(instance.getPluginInstanceParams());
- AlertResult alertResult = alertChannel.process(alertInfo);
-
- if (alertResult == null) {
- String message = String.format("Alert Plugin %s send error : return alertResult value is null", pluginInstanceName);
- alertResultExtend.setStatus(String.valueOf(false));
- alertResultExtend.setMessage(message);
- logger.info("Alert Plugin {} send error : return alertResult value is null", pluginInstanceName);
- } else if (!Boolean.parseBoolean(String.valueOf(alertResult.getStatus()))) {
- alertResultExtend.setStatus(String.valueOf(false));
- alertResultExtend.setMessage(alertResult.getMessage());
- logger.info("Alert Plugin {} send error : {}", pluginInstanceName, alertResult.getMessage());
- } else {
- String message = String.format("Alert Plugin %s send success", pluginInstanceName);
- alertResultExtend.setStatus(String.valueOf(true));
- alertResultExtend.setMessage(message);
- logger.info("Alert Plugin {} send success", pluginInstanceName);
- }
- return alertResultExtend;
- }
-
}
diff --git a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/AlertTemplate.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplate.java
similarity index 72%
rename from dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/AlertTemplate.java
rename to dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplate.java
index dec993d4d0..81b5e65f27 100644
--- a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/AlertTemplate.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplate.java
@@ -14,10 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package org.apache.dolphinscheduler.alert.template;
-package org.apache.dolphinscheduler.plugin.alert.email.template;
-
-import org.apache.dolphinscheduler.spi.alert.ShowType;
+import org.apache.dolphinscheduler.common.enums.ShowType;
/**
* alert message template
@@ -26,22 +25,20 @@ public interface AlertTemplate {
/**
* get a message from a specified alert template
- *
- * @param content alert message content
- * @param showType show type
- * @param showAll whether to show all
+ * @param content alert message content
+ * @param showType show type
+ * @param showAll whether to show all
* @return a message from a specified alert template
*/
- String getMessageFromTemplate(String content, ShowType showType, boolean showAll);
+ String getMessageFromTemplate(String content, ShowType showType,boolean showAll);
/**
* default showAll is true
- *
- * @param content alert message content
+ * @param content alert message content
* @param showType show type
* @return a message from a specified alert template
*/
- default String getMessageFromTemplate(String content, ShowType showType) {
- return getMessageFromTemplate(content, showType, true);
+ default String getMessageFromTemplate(String content,ShowType showType){
+ return getMessageFromTemplate(content,showType,true);
}
}
diff --git a/dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/params/base/DataType.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactory.java
similarity index 64%
rename from dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/params/base/DataType.java
rename to dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactory.java
index 2b94ac1a73..d38463123e 100644
--- a/dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/params/base/DataType.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactory.java
@@ -15,25 +15,24 @@
* limitations under the License.
*/
-package org.apache.dolphinscheduler.spi.params.base;
+package org.apache.dolphinscheduler.alert.template;
+
+import org.apache.dolphinscheduler.alert.template.impl.DefaultHTMLTemplate;
/**
- * param datetype
+ * the alert template factory
*/
-public enum DataType {
-
- STRING("string"),
-
- NUMBER("number");
+public class AlertTemplateFactory {
- private String dataType;
-
- DataType(String dataType) {
- this.dataType = dataType;
+ private AlertTemplateFactory() {
}
- public String getDataType() {
- return this.dataType;
+ /**
+ * get a template from alert.properties conf file
+ *
+ * @return a template, default is DefaultHTMLTemplate
+ */
+ public static AlertTemplate getMessageTemplate() {
+ return new DefaultHTMLTemplate();
}
-
}
diff --git a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplate.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplate.java
similarity index 66%
rename from dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplate.java
rename to dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplate.java
index 06decd6ffc..f590849660 100644
--- a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplate.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplate.java
@@ -15,19 +15,21 @@
* limitations under the License.
*/
-package org.apache.dolphinscheduler.plugin.alert.email.template;
+package org.apache.dolphinscheduler.alert.template.impl;
-import static java.util.Objects.requireNonNull;
+import static org.apache.dolphinscheduler.common.utils.Preconditions.checkNotNull;
-import org.apache.dolphinscheduler.plugin.alert.email.EmailConstants;
-import org.apache.dolphinscheduler.spi.alert.ShowType;
-import org.apache.dolphinscheduler.spi.utils.JSONUtils;
-import org.apache.dolphinscheduler.spi.utils.StringUtils;
+import org.apache.dolphinscheduler.alert.template.AlertTemplate;
+import org.apache.dolphinscheduler.alert.utils.Constants;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.common.utils.JSONUtils;
+import org.apache.dolphinscheduler.common.utils.StringUtils;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import org.slf4j.Logger;
@@ -50,7 +52,7 @@ public class DefaultHTMLTemplate implements AlertTemplate {
case TABLE:
return getTableTypeMessage(content, showAll);
case TEXT:
- return getTextTypeMessage(content, showAll);
+ return getTextTypeMessage(content);
default:
throw new IllegalArgumentException(String.format("not support showType: %s in DefaultHTMLTemplate", showType));
}
@@ -68,8 +70,8 @@ public class DefaultHTMLTemplate implements AlertTemplate {
if (StringUtils.isNotEmpty(content)) {
List mapItemsList = JSONUtils.toList(content, LinkedHashMap.class);
- if (!showAll && mapItemsList.size() > EmailConstants.NUMBER_1000) {
- mapItemsList = mapItemsList.subList(0, EmailConstants.NUMBER_1000);
+ if (!showAll && mapItemsList.size() > Constants.NUMBER_1000) {
+ mapItemsList = mapItemsList.subList(0, Constants.NUMBER_1000);
}
StringBuilder contents = new StringBuilder(200);
@@ -79,21 +81,21 @@ public class DefaultHTMLTemplate implements AlertTemplate {
String title = "";
for (LinkedHashMap mapItems : mapItemsList) {
- Set> entries = mapItems.entrySet();
+ Set> entries = mapItems.entrySet();
- Iterator> iterator = entries.iterator();
+ Iterator> iterator = entries.iterator();
- StringBuilder t = new StringBuilder(EmailConstants.TR);
- StringBuilder cs = new StringBuilder(EmailConstants.TR);
+ StringBuilder t = new StringBuilder(Constants.TR);
+ StringBuilder cs = new StringBuilder(Constants.TR);
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
- t.append(EmailConstants.TH).append(entry.getKey()).append(EmailConstants.TH_END);
- cs.append(EmailConstants.TD).append(String.valueOf(entry.getValue())).append(EmailConstants.TD_END);
+ t.append(Constants.TH).append(entry.getKey()).append(Constants.TH_END);
+ cs.append(Constants.TD).append(String.valueOf(entry.getValue())).append(Constants.TD_END);
}
- t.append(EmailConstants.TR_END);
- cs.append(EmailConstants.TR_END);
+ t.append(Constants.TR_END);
+ cs.append(Constants.TR_END);
if (flag) {
title = t.toString();
}
@@ -111,18 +113,17 @@ public class DefaultHTMLTemplate implements AlertTemplate {
* get alert message which type is TEXT
*
* @param content message content
- * @param showAll weather to show all
* @return alert message
*/
- private String getTextTypeMessage(String content, boolean showAll) {
+ private String getTextTypeMessage(String content) {
if (StringUtils.isNotEmpty(content)) {
ArrayNode list = JSONUtils.parseArray(content);
StringBuilder contents = new StringBuilder(100);
for (JsonNode jsonNode : list) {
- contents.append(EmailConstants.TR);
- contents.append(EmailConstants.TD).append(jsonNode.toString()).append(EmailConstants.TD_END);
- contents.append(EmailConstants.TR_END);
+ contents.append(Constants.TR);
+ contents.append(Constants.TD).append(jsonNode.toString()).append(Constants.TD_END);
+ contents.append(Constants.TR_END);
}
return getMessageFromHtmlTemplate(null, contents.toString());
@@ -135,16 +136,16 @@ public class DefaultHTMLTemplate implements AlertTemplate {
/**
* get alert message from a html template
*
- * @param title message title
+ * @param title message title
* @param content message content
* @return alert message which use html template
*/
private String getMessageFromHtmlTemplate(String title, String content) {
- requireNonNull(content, "content must not null");
- String htmlTableThead = StringUtils.isEmpty(title) ? "" : String.format("%s\n", title);
+ checkNotNull(content);
+ String htmlTableThead = StringUtils.isEmpty(title) ? "" : String.format("%s%n", title);
- return EmailConstants.HTML_HEADER_PREFIX + htmlTableThead + content + EmailConstants.TABLE_BODY_HTML_TAIL;
+ return Constants.HTML_HEADER_PREFIX + htmlTableThead + content + Constants.TABLE_BODY_HTML_TAIL;
}
}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/Constants.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/Constants.java
index 8041fa565f..c0f916a809 100644
--- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/Constants.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/Constants.java
@@ -30,9 +30,177 @@ public class Constants {
*/
public static final String ALERT_PROPERTIES_PATH = "/alert.properties";
- /** default alert plugin dir **/
- public static final String ALERT_PLUGIN_PATH = "./lib/plugin/alert";
+ public static final String DATA_SOURCE_PROPERTIES_PATH = "/dao/data_source.properties";
+
+ public static final String SINGLE_SLASH = "/";
+
+ /**
+ * UTF-8
+ */
+ public static final String UTF_8 = "UTF-8";
+
+ public static final String STATUS = "status";
+
+ public static final String MESSAGE = "message";
+
+ public static final String MAIL_PROTOCOL = "mail.protocol";
+
+ public static final String MAIL_SERVER_HOST = "mail.server.host";
+
+ public static final String MAIL_SERVER_PORT = "mail.server.port";
+
+ public static final String MAIL_SENDER = "mail.sender";
+
+ public static final String MAIL_USER = "mail.user";
+
+ public static final String MAIL_PASSWD = "mail.passwd";
+
+ public static final String XLS_FILE_PATH = "xls.file.path";
+
+ public static final String MAIL_HOST = "mail.smtp.host";
+
+ public static final String MAIL_PORT = "mail.smtp.port";
+
+ public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
+
+ public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
+
+ public static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable";
+
+ public static final String MAIL_SMTP_SSL_ENABLE = "mail.smtp.ssl.enable";
+
+ public static final String MAIL_SMTP_SSL_TRUST = "mail.smtp.ssl.trust";
+
+ public static final String TEXT_HTML_CHARSET_UTF_8 = "text/html;charset=utf-8";
+
+ public static final String STRING_TRUE = "true";
+
+ public static final String EXCEL_SUFFIX_XLS = ".xls";
+
+ public static final int NUMBER_1000 = 1000;
+
+ public static final String SPRING_DATASOURCE_DRIVER_CLASS_NAME = "spring.datasource.driver-class-name";
+
+ public static final String SPRING_DATASOURCE_URL = "spring.datasource.url";
+
+ public static final String SPRING_DATASOURCE_USERNAME = "spring.datasource.username";
+
+ public static final String SPRING_DATASOURCE_PASSWORD = "spring.datasource.password";
+
+ public static final String SPRING_DATASOURCE_VALIDATION_QUERY_TIMEOUT = "spring.datasource.validationQueryTimeout";
+
+ public static final String SPRING_DATASOURCE_INITIAL_SIZE = "spring.datasource.initialSize";
+
+ public static final String SPRING_DATASOURCE_MIN_IDLE = "spring.datasource.minIdle";
+
+ public static final String SPRING_DATASOURCE_MAX_ACTIVE = "spring.datasource.maxActive";
+
+ public static final String SPRING_DATASOURCE_MAX_WAIT = "spring.datasource.maxWait";
+
+ public static final String SPRING_DATASOURCE_TIME_BETWEEN_EVICTION_RUNS_MILLIS = "spring.datasource.timeBetweenEvictionRunsMillis";
+
+ public static final String SPRING_DATASOURCE_MIN_EVICTABLE_IDLE_TIME_MILLIS = "spring.datasource.minEvictableIdleTimeMillis";
+
+ public static final String SPRING_DATASOURCE_VALIDATION_QUERY = "spring.datasource.validationQuery";
+
+ public static final String SPRING_DATASOURCE_TEST_WHILE_IDLE = "spring.datasource.testWhileIdle";
+
+ public static final String SPRING_DATASOURCE_TEST_ON_BORROW = "spring.datasource.testOnBorrow";
+
+ public static final String SPRING_DATASOURCE_TEST_ON_RETURN = "spring.datasource.testOnReturn";
+
+ public static final String SPRING_DATASOURCE_POOL_PREPARED_STATEMENTS = "spring.datasource.poolPreparedStatements";
+
+ public static final String SPRING_DATASOURCE_DEFAULT_AUTO_COMMIT = "spring.datasource.defaultAutoCommit";
+
+ public static final String SPRING_DATASOURCE_KEEP_ALIVE = "spring.datasource.keepAlive";
+
+ public static final String SPRING_DATASOURCE_MAX_POOL_PREPARED_STATEMENT_PER_CONNECTION_SIZE = "spring.datasource.maxPoolPreparedStatementPerConnectionSize";
+
+ public static final String DEVELOPMENT = "development";
+
+ public static final String TR = "";
+
+ public static final String TD = "";
+
+ public static final String TD_END = " | ";
+
+ public static final String TR_END = "
";
+
+ public static final String TITLE = "title";
+
+ public static final String CONTENT = "content";
+
+ public static final String TH = "";
+
+ public static final String TH_END = " | ";
public static final int ALERT_SCAN_INTERVAL = 5000;
+ public static final String MARKDOWN_QUOTE = ">";
+
+ public static final String MARKDOWN_ENTER = "\n";
+
+ public static final String ENTERPRISE_WECHAT_ENABLE = "enterprise.wechat.enable";
+
+ public static final String ENTERPRISE_WECHAT_CORP_ID = "enterprise.wechat.corp.id";
+
+ public static final String ENTERPRISE_WECHAT_SECRET = "enterprise.wechat.secret";
+
+ public static final String ENTERPRISE_WECHAT_TOKEN_URL = "enterprise.wechat.token.url";
+
+ public static final String ENTERPRISE_WECHAT_PUSH_URL = "enterprise.wechat.push.url";
+
+ public static final String ENTERPRISE_WECHAT_TEAM_SEND_MSG = "enterprise.wechat.team.send.msg";
+
+ public static final String ENTERPRISE_WECHAT_USER_SEND_MSG = "enterprise.wechat.user.send.msg";
+
+ public static final String ENTERPRISE_WECHAT_AGENT_ID = "enterprise.wechat.agent.id";
+
+ public static final String ENTERPRISE_WECHAT_USERS = "enterprise.wechat.users";
+
+
+ public static final String DINGTALK_WEBHOOK = "dingtalk.webhook";
+
+ public static final String DINGTALK_KEYWORD = "dingtalk.keyword";
+
+ public static final String DINGTALK_PROXY_ENABLE = "dingtalk.isEnableProxy";
+
+ public static final String DINGTALK_PROXY = "dingtalk.proxy";
+
+ public static final String DINGTALK_PORT = "dingtalk.port";
+
+ public static final String DINGTALK_USER = "dingtalk.user";
+
+ public static final String DINGTALK_PASSWORD = "dingtalk.password";
+
+ public static final String DINGTALK_ENABLE = "dingtalk.isEnable";
+
+ public static final String HTML_HEADER_PREFIX = ""
+ + "dolphinscheduler"
+ + ""
+ + ""
+ + "/head> ";
+
+ public static final String TABLE_BODY_HTML_TAIL = "
";
+
+ /**
+ * plugin config
+ */
+ public static final String PLUGIN_DIR = "plugin.dir";
+
+ public static final String PLUGIN_DEFAULT_EMAIL_ID = "email";
+
+ public static final String PLUGIN_DEFAULT_EMAIL_CH = "邮件";
+
+ public static final String PLUGIN_DEFAULT_EMAIL_EN = "email";
+
+ public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERS = "receivers";
+
+ public static final String PLUGIN_DEFAULT_EMAIL_RECEIVERCCS = "receiverCcs";
+
+ public static final String RETMAP_MSG = "msg";
+
}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtils.java
new file mode 100644
index 0000000000..50a62e46fd
--- /dev/null
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtils.java
@@ -0,0 +1,141 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+import org.apache.dolphinscheduler.common.utils.*;
+
+import org.apache.commons.codec.binary.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * DingTalkUtils utils
+ * support send msg to ding talk by robot message push function.
+ * support PROXY setting
+ */
+public class DingTalkUtils {
+ public static final Logger logger = LoggerFactory.getLogger(DingTalkUtils.class);
+
+ public static final boolean IS_ENABLE_DING_TALK = PropertyUtils.getBoolean(Constants.DINGTALK_ENABLE);
+ private static final String DING_TASK_URL = PropertyUtils.getString(Constants.DINGTALK_WEBHOOK);
+ private static final String KEYWORD = PropertyUtils.getString(Constants.DINGTALK_KEYWORD);
+ private static final Boolean IS_ENABLE_PROXY = PropertyUtils.getBoolean(Constants.DINGTALK_PROXY_ENABLE);
+ private static final String PROXY = PropertyUtils.getString(Constants.DINGTALK_PROXY);
+ private static final String USER = PropertyUtils.getString(Constants.DINGTALK_USER);
+ private static final String PASSWD = PropertyUtils.getString(Constants.DINGTALK_PASSWORD);
+ private static final Integer PORT = PropertyUtils.getInt(Constants.DINGTALK_PORT);
+
+ private DingTalkUtils() {
+ throw new IllegalStateException(DingTalkUtils.class.getName());
+ }
+
+ /**
+ * send message interface
+ * only support text message format now.
+ *
+ * @param msg message context to send
+ * @param charset charset type
+ * @return result of sending msg
+ * @throws IOException the IOException
+ */
+ public static String sendDingTalkMsg(String msg, String charset) throws IOException {
+ String msgToJson = textToJsonString(msg + "#" + KEYWORD);
+ HttpPost httpPost = constructHttpPost(msgToJson, charset);
+
+ CloseableHttpClient httpClient;
+ if (Boolean.TRUE.equals(IS_ENABLE_PROXY)) {
+ httpClient = getProxyClient();
+ RequestConfig rcf = getProxyConfig();
+ httpPost.setConfig(rcf);
+ } else {
+ httpClient = getDefaultClient();
+ }
+
+ try {
+ CloseableHttpResponse response = httpClient.execute(httpPost);
+ String resp;
+ try {
+ HttpEntity entity = response.getEntity();
+ resp = EntityUtils.toString(entity, charset);
+ EntityUtils.consume(entity);
+ } finally {
+ response.close();
+ }
+ logger.info("Ding Talk send [{}], resp:{%s}", msg);
+ return resp;
+ } finally {
+ httpClient.close();
+ }
+ }
+
+ public static HttpPost constructHttpPost(String msg, String charset) {
+ HttpPost post = new HttpPost(DING_TASK_URL);
+ StringEntity entity = new StringEntity(msg, charset);
+ post.setEntity(entity);
+ post.addHeader("Content-Type", "application/json; charset=utf-8");
+ return post;
+ }
+
+ public static CloseableHttpClient getProxyClient() {
+ HttpHost httpProxy = new HttpHost(PROXY, PORT);
+ CredentialsProvider provider = new BasicCredentialsProvider();
+ provider.setCredentials(new AuthScope(httpProxy), new UsernamePasswordCredentials(USER, PASSWD));
+ return HttpClients.custom().setDefaultCredentialsProvider(provider).build();
+ }
+
+ public static CloseableHttpClient getDefaultClient() {
+ return HttpClients.createDefault();
+ }
+
+ public static RequestConfig getProxyConfig() {
+ HttpHost httpProxy = new HttpHost(PROXY, PORT);
+ return RequestConfig.custom().setProxy(httpProxy).build();
+ }
+
+ public static String textToJsonString(String text) {
+ Map items = new HashMap<>();
+ items.put("msgtype", "text");
+ Map textContent = new HashMap<>();
+ byte[] byt = StringUtils.getBytesUtf8(text);
+ String txt = StringUtils.newStringUtf8(byt);
+ textContent.put("content", txt);
+ items.put("text", textContent);
+
+ return JSONUtils.toJsonString(items);
+
+ }
+
+}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java
new file mode 100644
index 0000000000..aeb6671791
--- /dev/null
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java
@@ -0,0 +1,286 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.common.utils.JSONUtils;
+import org.apache.dolphinscheduler.common.utils.StringUtils;
+import org.apache.dolphinscheduler.plugin.model.AlertData;
+
+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.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Enterprise WeChat utils
+ */
+public class EnterpriseWeChatUtils {
+
+ public static final Logger logger = LoggerFactory.getLogger(EnterpriseWeChatUtils.class);
+ public static final String ENTERPRISE_WE_CHAT_AGENT_ID = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_AGENT_ID);
+ public static final String ENTERPRISE_WE_CHAT_USERS = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_USERS);
+ private static final String ENTERPRISE_WE_CHAT_CORP_ID = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_CORP_ID);
+ private static final String ENTERPRISE_WE_CHAT_SECRET = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_SECRET);
+ private static final String ENTERPRISE_WE_CHAT_TOKEN_URL = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_TOKEN_URL);
+ private static final String ENTERPRISE_WE_CHAT_TOKEN_URL_REPLACE = ENTERPRISE_WE_CHAT_TOKEN_URL == null ? null : ENTERPRISE_WE_CHAT_TOKEN_URL
+ .replaceAll("\\{corpId}", ENTERPRISE_WE_CHAT_CORP_ID)
+ .replaceAll("\\{secret}", ENTERPRISE_WE_CHAT_SECRET);
+ private static final String ENTERPRISE_WE_CHAT_PUSH_URL = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_PUSH_URL);
+ private static final String ENTERPRISE_WE_CHAT_TEAM_SEND_MSG = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_TEAM_SEND_MSG);
+ private static final String ENTERPRISE_WE_CHAT_USER_SEND_MSG = PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_USER_SEND_MSG);
+
+ private static final String AGENT_ID_REG_EXP = "\\{agentId}";
+ private static final String MSG_REG_EXP = "\\{msg}";
+ private static final String USER_REG_EXP = "\\{toUser}";
+
+ private EnterpriseWeChatUtils() {
+ throw new IllegalStateException(EnterpriseWeChatUtils.class.getName());
+ }
+
+ /**
+ * get Enterprise WeChat is enable
+ *
+ * @return isEnable
+ */
+ public static boolean isEnable() {
+ Boolean isEnable = null;
+ try {
+ isEnable = PropertyUtils.getBoolean(Constants.ENTERPRISE_WECHAT_ENABLE);
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ }
+ if (isEnable == null) {
+ return false;
+ }
+ return isEnable;
+ }
+
+ /**
+ * get Enterprise WeChat token info
+ *
+ * @return token string info
+ * @throws IOException the IOException
+ */
+ public static String getToken() throws IOException {
+ String resp;
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ try {
+ HttpGet httpGet = new HttpGet(ENTERPRISE_WE_CHAT_TOKEN_URL_REPLACE);
+ CloseableHttpResponse response = httpClient.execute(httpGet);
+ try {
+ HttpEntity entity = response.getEntity();
+ resp = EntityUtils.toString(entity, Constants.UTF_8);
+ EntityUtils.consume(entity);
+ } finally {
+ response.close();
+ }
+
+ Map map = JSONUtils.toMap(resp);
+ return map == null ? null : map.get("access_token");
+ } finally {
+ httpClient.close();
+ }
+ }
+
+ /**
+ * make team single Enterprise WeChat message
+ *
+ * @param toParty the toParty
+ * @param agentId the agentId
+ * @param msg the msg
+ * @return Enterprise WeChat send message
+ */
+ public static String makeTeamSendMsg(String toParty, String agentId, String msg) {
+ return ENTERPRISE_WE_CHAT_TEAM_SEND_MSG.replaceAll("\\{toParty}", toParty)
+ .replaceAll(AGENT_ID_REG_EXP, agentId)
+ .replaceAll(MSG_REG_EXP, msg);
+ }
+
+ /**
+ * make team multi Enterprise WeChat message
+ *
+ * @param toParty the toParty
+ * @param agentId the agentId
+ * @param msg the msg
+ * @return Enterprise WeChat send message
+ */
+ public static String makeTeamSendMsg(Collection toParty, String agentId, String msg) {
+ String listParty = FuncUtils.mkString(toParty, "|");
+ return ENTERPRISE_WE_CHAT_TEAM_SEND_MSG.replaceAll("\\{toParty}", listParty)
+ .replaceAll(AGENT_ID_REG_EXP, agentId)
+ .replaceAll(MSG_REG_EXP, msg);
+ }
+
+ /**
+ * make team single user message
+ *
+ * @param toUser the toUser
+ * @param agentId the agentId
+ * @param msg the msg
+ * @return Enterprise WeChat send message
+ */
+ public static String makeUserSendMsg(String toUser, String agentId, String msg) {
+ return ENTERPRISE_WE_CHAT_USER_SEND_MSG.replaceAll(USER_REG_EXP, toUser)
+ .replaceAll(AGENT_ID_REG_EXP, agentId)
+ .replaceAll(MSG_REG_EXP, msg);
+ }
+
+ /**
+ * make team multi user message
+ *
+ * @param toUser the toUser
+ * @param agentId the agentId
+ * @param msg the msg
+ * @return Enterprise WeChat send message
+ */
+ public static String makeUserSendMsg(Collection toUser, String agentId, String msg) {
+ String listUser = FuncUtils.mkString(toUser, "|");
+ return ENTERPRISE_WE_CHAT_USER_SEND_MSG.replaceAll(USER_REG_EXP, listUser)
+ .replaceAll(AGENT_ID_REG_EXP, agentId)
+ .replaceAll(MSG_REG_EXP, msg);
+ }
+
+ /**
+ * send Enterprise WeChat
+ *
+ * @param charset the charset
+ * @param data the data
+ * @param token the token
+ * @return Enterprise WeChat resp, demo: {"errcode":0,"errmsg":"ok","invaliduser":""}
+ * @throws IOException the IOException
+ */
+ public static String sendEnterpriseWeChat(String charset, String data, String token) throws IOException {
+ String enterpriseWeChatPushUrlReplace = ENTERPRISE_WE_CHAT_PUSH_URL.replaceAll("\\{token}", token);
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(enterpriseWeChatPushUrlReplace);
+ httpPost.setEntity(new StringEntity(data, charset));
+ CloseableHttpResponse response = httpClient.execute(httpPost);
+ String resp;
+ try {
+ HttpEntity entity = response.getEntity();
+ resp = EntityUtils.toString(entity, charset);
+ EntityUtils.consume(entity);
+ } finally {
+ response.close();
+ }
+ logger.info("Enterprise WeChat send [{}], param:{}, resp:{}",
+ ENTERPRISE_WE_CHAT_PUSH_URL, data, resp);
+ return resp;
+ } finally {
+ httpClient.close();
+ }
+ }
+
+ /**
+ * convert table to markdown style
+ *
+ * @param title the title
+ * @param content the content
+ * @return markdown table content
+ */
+ public static String markdownTable(String title, String content) {
+ List mapItemsList = JSONUtils.toList(content, LinkedHashMap.class);
+ StringBuilder contents = new StringBuilder(200);
+
+ if (null != mapItemsList) {
+ for (LinkedHashMap mapItems : mapItemsList) {
+ Set> entries = mapItems.entrySet();
+ Iterator> iterator = entries.iterator();
+ StringBuilder t = new StringBuilder(String.format("`%s`%s", title, Constants.MARKDOWN_ENTER));
+
+ while (iterator.hasNext()) {
+
+ Map.Entry entry = iterator.next();
+ t.append(Constants.MARKDOWN_QUOTE);
+ t.append(entry.getKey()).append(":").append(entry.getValue());
+ t.append(Constants.MARKDOWN_ENTER);
+ }
+ contents.append(t);
+ }
+ }
+ return contents.toString();
+ }
+
+ /**
+ * convert text to markdown style
+ *
+ * @param title the title
+ * @param content the content
+ * @return markdown text
+ */
+ public static String markdownText(String title, String content) {
+ if (StringUtils.isNotEmpty(content)) {
+ List mapItemsList = JSONUtils.toList(content, LinkedHashMap.class);
+ if (null != mapItemsList) {
+ StringBuilder contents = new StringBuilder(100);
+ contents.append(String.format("`%s`%n", title));
+ for (LinkedHashMap mapItems : mapItemsList) {
+
+ Set> entries = mapItems.entrySet();
+ Iterator> iterator = entries.iterator();
+ while (iterator.hasNext()) {
+ Map.Entry entry = iterator.next();
+ contents.append(Constants.MARKDOWN_QUOTE);
+ contents.append(entry.getKey()).append(":").append(entry.getValue());
+ contents.append(Constants.MARKDOWN_ENTER);
+ }
+
+ }
+ return contents.toString();
+ }
+
+ }
+ return null;
+ }
+
+ /**
+ * Determine the mardown style based on the show type of the alert
+ *
+ * @return the markdown alert table/text
+ */
+ public static String markdownByAlert(AlertData alert) {
+ String result = "";
+ if (alert.getShowType().equals(ShowType.TABLE.getDescp())) {
+ result = markdownTable(alert.getTitle(), alert.getContent());
+ } else if (alert.getShowType().equals(ShowType.TEXT.getDescp())) {
+ result = markdownText(alert.getTitle(), alert.getContent());
+ }
+ return result;
+
+ }
+
+}
diff --git a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/ExcelUtils.java
similarity index 87%
rename from dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtils.java
rename to dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/ExcelUtils.java
index 1579f9548e..76ce66ac2f 100644
--- a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/main/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtils.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/ExcelUtils.java
@@ -15,11 +15,11 @@
* limitations under the License.
*/
-package org.apache.dolphinscheduler.plugin.alert.email;
+package org.apache.dolphinscheduler.alert.utils;
-import org.apache.dolphinscheduler.spi.utils.JSONUtils;
+import org.apache.dolphinscheduler.common.utils.CollectionUtils;
+import org.apache.dolphinscheduler.common.utils.JSONUtils;
-import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
@@ -31,7 +31,6 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -44,12 +43,12 @@ import org.slf4j.LoggerFactory;
*/
public class ExcelUtils {
- public ExcelUtils() {
- throw new IllegalStateException("Utility class");
- }
-
private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
+ private ExcelUtils() {
+ throw new IllegalStateException(ExcelUtils.class.getName());
+ }
+
/**
* generate excel file
*
@@ -72,9 +71,7 @@ public class ExcelUtils {
List headerList = new ArrayList<>();
- Iterator> iter = headerMap.entrySet().iterator();
- while (iter.hasNext()) {
- Map.Entry en = iter.next();
+ for (Map.Entry en : headerMap.entrySet()) {
headerList.add(en.getKey());
}
@@ -125,12 +122,11 @@ public class ExcelUtils {
}
//setting file output
- fos = new FileOutputStream(xlsFilePath + EmailConstants.SINGLE_SLASH + title + EmailConstants.EXCEL_SUFFIX_XLS);
+ fos = new FileOutputStream(xlsFilePath + Constants.SINGLE_SLASH + title + Constants.EXCEL_SUFFIX_XLS);
wb.write(fos);
} catch (Exception e) {
- logger.error("generate excel error", e);
throw new RuntimeException("generate excel error", e);
} finally {
if (wb != null) {
@@ -150,4 +146,4 @@ public class ExcelUtils {
}
}
-}
\ No newline at end of file
+}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/MailUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/MailUtils.java
new file mode 100644
index 0000000000..f57481bd0c
--- /dev/null
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/MailUtils.java
@@ -0,0 +1,375 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+import org.apache.dolphinscheduler.alert.template.AlertTemplate;
+import org.apache.dolphinscheduler.alert.template.AlertTemplateFactory;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.common.utils.CollectionUtils;
+import org.apache.dolphinscheduler.common.utils.StringUtils;
+
+import org.apache.commons.mail.EmailException;
+import org.apache.commons.mail.HtmlEmail;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.mail.Authenticator;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.PasswordAuthentication;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+import javax.mail.internet.MimeUtility;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * mail utils
+ */
+public class MailUtils {
+
+ public static final Logger logger = LoggerFactory.getLogger(MailUtils.class);
+
+ public static final String MAIL_PROTOCOL = PropertyUtils.getString(Constants.MAIL_PROTOCOL);
+
+ public static final String MAIL_SERVER_HOST = PropertyUtils.getString(Constants.MAIL_SERVER_HOST);
+
+ public static final Integer MAIL_SERVER_PORT = PropertyUtils.getInt(Constants.MAIL_SERVER_PORT);
+
+ public static final String MAIL_SENDER = PropertyUtils.getString(Constants.MAIL_SENDER);
+
+ public static final String MAIL_USER = PropertyUtils.getString(Constants.MAIL_USER);
+
+ public static final String MAIL_PASSWD = PropertyUtils.getString(Constants.MAIL_PASSWD);
+
+ public static final Boolean MAIL_USE_START_TLS = PropertyUtils.getBoolean(Constants.MAIL_SMTP_STARTTLS_ENABLE);
+
+ public static final Boolean MAIL_USE_SSL = PropertyUtils.getBoolean(Constants.MAIL_SMTP_SSL_ENABLE);
+
+ public static final String XLS_FILE_PATH = PropertyUtils.getString(Constants.XLS_FILE_PATH, "/tmp/xls");
+
+ public static final String STARTTLS_ENABLE = PropertyUtils.getString(Constants.MAIL_SMTP_STARTTLS_ENABLE);
+
+ public static final Boolean SSL_ENABLE = PropertyUtils.getBoolean(Constants.MAIL_SMTP_SSL_ENABLE);
+
+ public static final String SSL_TRUST = PropertyUtils.getString(Constants.MAIL_SMTP_SSL_TRUST);
+
+ public static final AlertTemplate alertTemplate = AlertTemplateFactory.getMessageTemplate();
+
+ //Solve the problem of messy Chinese name in excel attachment
+ static {
+ System.setProperty("mail.mime.splitlongparameters", "false");
+ }
+
+ private MailUtils() {
+ throw new IllegalStateException(MailUtils.class.getName());
+ }
+
+ /**
+ * send mail to receivers
+ *
+ * @param receivers the receiver list
+ * @param title the title
+ * @param content the content
+ * @param showType the show type
+ * @return the result map
+ */
+ public static Map sendMails(Collection receivers, String title, String content, String showType) {
+ return sendMails(receivers, null, title, content, showType);
+ }
+
+ /**
+ * send mail
+ *
+ * @param receivers the receiver list
+ * @param receiversCc cc list
+ * @param title the title
+ * @param content the content
+ * @param showType the show type
+ * @return the send result
+ */
+ public static Map sendMails(Collection receivers, Collection receiversCc, String title, String content, String showType) {
+ Map retMap = new HashMap<>();
+ retMap.put(Constants.STATUS, false);
+
+ // if there is no receivers && no receiversCc, no need to process
+ if (CollectionUtils.isEmpty(receivers) && CollectionUtils.isEmpty(receiversCc)) {
+ return retMap;
+ }
+
+ receivers.removeIf(StringUtils::isEmpty);
+
+ if (showType.equals(ShowType.TABLE.getDescp()) || showType.equals(ShowType.TEXT.getDescp())) {
+ // send email
+ HtmlEmail email = new HtmlEmail();
+
+ try {
+ Session session = getSession();
+ email.setMailSession(session);
+ email.setFrom(MAIL_SENDER);
+ email.setCharset(Constants.UTF_8);
+ if (CollectionUtils.isNotEmpty(receivers)) {
+ // receivers mail
+ for (String receiver : receivers) {
+ email.addTo(receiver);
+ }
+ }
+
+ if (CollectionUtils.isNotEmpty(receiversCc)) {
+ //cc
+ for (String receiverCc : receiversCc) {
+ email.addCc(receiverCc);
+ }
+ }
+ // sender mail
+ return getStringObjectMap(title, content, showType, retMap, email);
+ } catch (Exception e) {
+ handleException(receivers, retMap, e);
+ }
+ } else if (showType.equals(ShowType.ATTACHMENT.getDescp()) || showType.equals(ShowType.TABLEATTACHMENT.getDescp())) {
+ try {
+
+ String partContent = (showType.equals(ShowType.ATTACHMENT.getDescp()) ? "Please see the attachment " + title + Constants.EXCEL_SUFFIX_XLS : htmlTable(content, false));
+
+ attachment(receivers, receiversCc, title, content, partContent);
+
+ retMap.put(Constants.STATUS, true);
+ return retMap;
+ } catch (Exception e) {
+ handleException(receivers, retMap, e);
+ return retMap;
+ }
+ }
+ return retMap;
+
+ }
+
+ /**
+ * html table content
+ *
+ * @param content the content
+ * @param showAll if show the whole content
+ * @return the html table form
+ */
+ private static String htmlTable(String content, boolean showAll) {
+ return alertTemplate.getMessageFromTemplate(content, ShowType.TABLE, showAll);
+ }
+
+ /**
+ * html table content
+ *
+ * @param content the content
+ * @return the html table form
+ */
+ private static String htmlTable(String content) {
+ return htmlTable(content, true);
+ }
+
+ /**
+ * html text content
+ *
+ * @param content the content
+ * @return text in html form
+ */
+ private static String htmlText(String content) {
+ return alertTemplate.getMessageFromTemplate(content, ShowType.TEXT);
+ }
+
+ /**
+ * send mail as Excel attachment
+ *
+ * @param receivers the receiver list
+ * @param title the title
+ */
+ private static void attachment(Collection receivers, Collection receiversCc, String title, String content, String partContent) throws Exception {
+ MimeMessage msg = getMimeMessage(receivers);
+
+ attachContent(receiversCc, title, content, partContent, msg);
+ }
+
+ /**
+ * get MimeMessage
+ *
+ * @param receivers receivers
+ * @return the MimeMessage
+ */
+ private static MimeMessage getMimeMessage(Collection receivers) throws MessagingException {
+
+ // 1. The first step in creating mail: creating session
+ Session session = getSession();
+ // Setting debug mode, can be turned off
+ session.setDebug(false);
+
+ // 2. creating mail: Creating a MimeMessage
+ MimeMessage msg = new MimeMessage(session);
+ // 3. set sender
+ msg.setFrom(new InternetAddress(MAIL_SENDER));
+ // 4. set receivers
+ for (String receiver : receivers) {
+ msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
+ }
+ return msg;
+ }
+
+ /**
+ * get session
+ *
+ * @return the new Session
+ */
+ private static Session getSession() {
+ Properties props = new Properties();
+ props.setProperty(Constants.MAIL_HOST, MAIL_SERVER_HOST);
+ props.setProperty(Constants.MAIL_PORT, String.valueOf(MAIL_SERVER_PORT));
+ props.setProperty(Constants.MAIL_SMTP_AUTH, Constants.STRING_TRUE);
+ props.setProperty(Constants.MAIL_TRANSPORT_PROTOCOL, MAIL_PROTOCOL);
+ props.setProperty(Constants.MAIL_SMTP_STARTTLS_ENABLE, STARTTLS_ENABLE);
+ if (Boolean.TRUE.equals(SSL_ENABLE)) {
+ props.setProperty(Constants.MAIL_SMTP_SSL_ENABLE, "true");
+ props.setProperty(Constants.MAIL_SMTP_SSL_TRUST, SSL_TRUST);
+ }
+
+ Authenticator auth = new Authenticator() {
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ // mail username and password
+ return new PasswordAuthentication(MAIL_USER, MAIL_PASSWD);
+ }
+ };
+
+ return Session.getInstance(props, auth);
+ }
+
+ /**
+ * attach content
+ *
+ * @param receiversCc the cc list
+ * @param title the title
+ * @param content the content
+ * @param partContent the partContent
+ * @param msg the message
+ */
+ private static void attachContent(Collection receiversCc, String title, String content, String partContent, MimeMessage msg) throws MessagingException, IOException {
+ /*
+ * set receiverCc
+ */
+ if (CollectionUtils.isNotEmpty(receiversCc)) {
+ for (String receiverCc : receiversCc) {
+ msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(receiverCc));
+ }
+ }
+
+ // set subject
+ msg.setSubject(title);
+ MimeMultipart partList = new MimeMultipart();
+ // set signature
+ MimeBodyPart part1 = new MimeBodyPart();
+ part1.setContent(partContent, Constants.TEXT_HTML_CHARSET_UTF_8);
+ // set attach file
+ MimeBodyPart part2 = new MimeBodyPart();
+ File file = new File(XLS_FILE_PATH + Constants.SINGLE_SLASH + title + Constants.EXCEL_SUFFIX_XLS);
+ if (!file.getParentFile().exists()) {
+ file.getParentFile().mkdirs();
+ }
+ // make excel file
+
+ ExcelUtils.genExcelFile(content, title, XLS_FILE_PATH);
+
+ part2.attachFile(file);
+ part2.setFileName(MimeUtility.encodeText(title + Constants.EXCEL_SUFFIX_XLS, Constants.UTF_8, "B"));
+ // add components to collection
+ partList.addBodyPart(part1);
+ partList.addBodyPart(part2);
+ msg.setContent(partList);
+ // 5. send Transport
+ Transport.send(msg);
+ // 6. delete saved file
+ deleteFile(file);
+ }
+
+ /**
+ * the string object map
+ *
+ * @param title the title
+ * @param content the content
+ * @param showType the showType
+ * @param retMap the result map
+ * @param email the email
+ * @return the result map
+ */
+ private static Map getStringObjectMap(String title, String content, String showType, Map retMap, HtmlEmail email) throws EmailException {
+
+ /*
+ * the subject of the message to be sent
+ */
+ email.setSubject(title);
+ /*
+ * to send information, you can use HTML tags in mail content because of the use of HtmlEmail
+ */
+ if (showType.equals(ShowType.TABLE.getDescp())) {
+ email.setMsg(htmlTable(content));
+ } else if (showType.equals(ShowType.TEXT.getDescp())) {
+ email.setMsg(htmlText(content));
+ }
+
+ // send
+ email.send();
+
+ retMap.put(Constants.STATUS, true);
+
+ return retMap;
+ }
+
+ /**
+ * file delete
+ *
+ * @param file the file to delete
+ */
+ public static void deleteFile(File file) {
+ if (file.exists()) {
+ if (file.delete()) {
+ logger.info("delete success: {}", file.getAbsolutePath() + file.getName());
+ } else {
+ logger.info("delete fail: {}", file.getAbsolutePath() + file.getName());
+ }
+ } else {
+ logger.info("file not exists: {}", file.getAbsolutePath() + file.getName());
+ }
+ }
+
+ /**
+ * handle exception
+ *
+ * @param receivers the receiver list
+ * @param retMap the result map
+ * @param e the exception
+ */
+ private static void handleException(Collection receivers, Map retMap, Exception e) {
+ logger.error("Send email to {} failed", receivers, e);
+ retMap.put(Constants.MESSAGE, "Send email to {" + String.join(",", receivers) + "} failed," + e.toString());
+ }
+}
diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java
index 16bcb6bd79..1ec781f27c 100644
--- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java
+++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java
@@ -88,7 +88,7 @@ public class PropertyUtils {
/**
* get property value
*
- * @param key property name
+ * @param key property name
* @param defaultVal default value
* @return property value
*/
diff --git a/dolphinscheduler-alert/src/main/resources/alert.properties b/dolphinscheduler-alert/src/main/resources/alert.properties
index cad64882a0..6eb701841c 100644
--- a/dolphinscheduler-alert/src/main/resources/alert.properties
+++ b/dolphinscheduler-alert/src/main/resources/alert.properties
@@ -15,19 +15,46 @@
# limitations under the License.
#
-#This configuration file configures the configuration parameters related to the AlertServer.
-#These parameters are only related to the AlertServer, and it has nothing to do with the specific Alert Plugin.
-#eg : max retry num.
-#eg : Alert Server Listener port
+#alert type is EMAIL/SMS
+alert.type=EMAIL
-#alert.plugin.dir config the Alert Plugin dir . AlertServer while find and load the Alert Plugin Jar from this dir when deploy and start AlertServer on the server .
-#eg :
-#alert.plugin.dir=/opt/soft/spi/lib/plugin/alert
+# mail server configuration
+mail.protocol=SMTP
+mail.server.host=xxx.xxx.com
+mail.server.port=25
+mail.sender=xxx@xxx.com
+mail.user=xxx@xxx.com
+mail.passwd=111111
+# TLS
+mail.smtp.starttls.enable=true
+# SSL
+mail.smtp.ssl.enable=false
+mail.smtp.ssl.trust=xxx.xxx.com
-#maven.local.repository=/Users/gaojun/Documents/jianguoyun/localRepository
+#xls file path,need create if not exist
+#xls.file.path=/tmp/xls
-#alert.plugin.binding config the Alert Plugin need be load when development and run in IDE
-#alert.plugin.binding=\
-# ./dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/pom.xml
+# Enterprise WeChat configuration
+enterprise.wechat.enable=false
+#enterprise.wechat.corp.id=xxxxxxx
+#enterprise.wechat.secret=xxxxxxx
+#enterprise.wechat.agent.id=xxxxxxx
+#enterprise.wechat.users=xxxxxxx
+#enterprise.wechat.token.url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={secret}
+#enterprise.wechat.push.url=https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}
+#enterprise.wechat.team.send.msg={\"toparty\":\"{toParty}\",\"agentid\":\"{agentId}\",\"msgtype\":\"text\",\"text\":{\"content\":\"{msg}\"},\"safe\":\"0\"}
+#enterprise.wechat.user.send.msg={\"touser\":\"{toUser}\",\"agentid\":\"{agentId}\",\"msgtype\":\"markdown\",\"markdown\":{\"content\":\"{msg}\"}}
+
+plugin.dir=/Users/xx/your/path/to/plugin/dir
+
+#ding talk configuration
+dingtalk.isEnable=flase
+dingtalk.webhook=https://oapi.dingtalk.com/robot/send?access_token=xxxxx
+dingtalk.keyword=
+dingtalk.proxy=
+dingtalk.port=80
+dingtalk.user=
+dingtalk.password=
+dingtalk.isEnableProxy=false
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/AlertServerTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/AlertServerTest.java
deleted file mode 100644
index a8ead79be9..0000000000
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/AlertServerTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert;
-
-import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
-import org.apache.dolphinscheduler.alert.plugin.DolphinPluginLoader;
-import org.apache.dolphinscheduler.alert.plugin.DolphinPluginManagerConfig;
-import org.apache.dolphinscheduler.alert.runner.AlertSender;
-import org.apache.dolphinscheduler.alert.utils.Constants;
-import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.DaoFactory;
-import org.apache.dolphinscheduler.dao.PluginDao;
-import org.apache.dolphinscheduler.remote.NettyRemotingServer;
-import org.apache.dolphinscheduler.spi.alert.AlertChannel;
-
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({AlertServer.class,DaoFactory.class})
-public class AlertServerTest {
-
- @Before
- public void before() {
-
- }
-
- @Test
- public void testMain() throws Exception {
- AlertDao alertDao = PowerMockito.mock(AlertDao.class);
- PowerMockito.mockStatic(DaoFactory.class);
- PowerMockito.when(DaoFactory.getDaoInstance(AlertDao.class)).thenReturn(alertDao);
-
- PluginDao pluginDao = PowerMockito.mock(PluginDao.class);
- PowerMockito.when(DaoFactory.getDaoInstance(PluginDao.class)).thenReturn(pluginDao);
-
- AlertChannel alertChannelMock = PowerMockito.mock(AlertChannel.class);
-
- AlertPluginManager alertPluginManager = PowerMockito.mock(AlertPluginManager.class);
- PowerMockito.whenNew(AlertPluginManager.class).withNoArguments().thenReturn(alertPluginManager);
- ConcurrentHashMap alertChannelMap = new ConcurrentHashMap<>();
- alertChannelMap.put("pluginName",alertChannelMock);
- PowerMockito.when(alertPluginManager.getAlertChannelMap()).thenReturn(alertChannelMap);
-
- DolphinPluginManagerConfig alertPluginManagerConfig = PowerMockito.mock(DolphinPluginManagerConfig.class);
- PowerMockito.whenNew(DolphinPluginManagerConfig.class).withNoArguments().thenReturn(alertPluginManagerConfig);
-
- NettyRemotingServer nettyRemotingServer = PowerMockito.mock(NettyRemotingServer.class);
- PowerMockito.whenNew(NettyRemotingServer.class).withAnyArguments().thenReturn(nettyRemotingServer);
- AlertSender alertSender = PowerMockito.mock(AlertSender.class);
- PowerMockito.whenNew(AlertSender.class).withAnyArguments().thenReturn(alertSender);
-
- DolphinPluginLoader dolphinPluginLoader = PowerMockito.mock(DolphinPluginLoader.class);
- PowerMockito.whenNew(DolphinPluginLoader.class).withAnyArguments().thenReturn(dolphinPluginLoader);
-
- AlertServer alertServer = AlertServer.getInstance();
- Assert.assertNotNull(alertServer);
-
- new Thread(() -> {
- alertServer.start(); })
- .start();
-
- Thread.sleep(5 * Constants.ALERT_SCAN_INTERVAL);
-
- alertServer.stop();
-
- }
-
-}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/AlertPluginManagerTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/AlertPluginManagerTest.java
deleted file mode 100644
index 5ed25cc004..0000000000
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/AlertPluginManagerTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert.plugin;
-
-import org.apache.dolphinscheduler.alert.AlertServer;
-import org.apache.dolphinscheduler.alert.utils.Constants;
-import org.apache.dolphinscheduler.alert.utils.PropertyUtils;
-import org.apache.dolphinscheduler.spi.utils.StringUtils;
-
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * AlertPluginManager Tester.
- */
-@Ignore
-public class AlertPluginManagerTest {
-
- private static final Logger logger = LoggerFactory.getLogger(AlertPluginManagerTest.class);
-
- @Test
- public void testLoadPlugins() throws Exception {
- logger.info("begin test AlertPluginManagerTest");
- AlertPluginManager alertPluginManager = new AlertPluginManager();
- DolphinPluginManagerConfig alertPluginManagerConfig = new DolphinPluginManagerConfig();
- String path = DolphinPluginLoader.class.getClassLoader().getResource("").getPath();
- alertPluginManagerConfig.setPlugins(path + "../../../dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/pom.xml");
- if (StringUtils.isNotBlank(PropertyUtils.getString(AlertServer.ALERT_PLUGIN_DIR))) {
- alertPluginManagerConfig.setInstalledPluginsDir(org.apache.dolphinscheduler.alert.utils.PropertyUtils.getString(AlertServer.ALERT_PLUGIN_DIR, Constants.ALERT_PLUGIN_PATH).trim());
- }
-
- if (StringUtils.isNotBlank(PropertyUtils.getString(AlertServer.MAVEN_LOCAL_REPOSITORY))) {
- alertPluginManagerConfig.setMavenLocalRepository(PropertyUtils.getString(AlertServer.MAVEN_LOCAL_REPOSITORY).trim());
- }
-
- DolphinPluginLoader alertPluginLoader = new DolphinPluginLoader(alertPluginManagerConfig, ImmutableList.of(alertPluginManager));
- try {
- alertPluginLoader.loadPlugins();
- } catch (Exception e) {
- throw new RuntimeException("load Alert Plugin Failed !", e);
- }
-
- Assert.assertNotNull(alertPluginManager.getAlertChannelFactoryMap().get("email alert"));
- }
-}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/DolphinPluginLoaderTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/DolphinPluginLoaderTest.java
deleted file mode 100644
index 5c792db451..0000000000
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/DolphinPluginLoaderTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert.plugin;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * DolphinPluginLoader Tester.
- */
-@Ignore
-public class DolphinPluginLoaderTest {
-
- @Before
- public void before() throws Exception {
- }
-
- @After
- public void after() throws Exception {
- }
-
- /**
- * Method: loadPlugins()
- */
- @Test
- public void testLoadPlugins() throws Exception {
- AlertPluginManager alertPluginManager = new AlertPluginManager();
- DolphinPluginManagerConfig alertPluginManagerConfig = new DolphinPluginManagerConfig();
- String path = DolphinPluginLoader.class.getClassLoader().getResource("").getPath();
- alertPluginManagerConfig.setPlugins(path + "../../../dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/pom.xml");
- DolphinPluginLoader alertPluginLoader = new DolphinPluginLoader(alertPluginManagerConfig, ImmutableList.of(alertPluginManager));
- try {
- alertPluginLoader.loadPlugins();
- } catch (Exception e) {
- throw new RuntimeException("load Alert Plugin Failed !", e);
- }
-
- Assert.assertNotNull(alertPluginManager.getAlertChannelFactoryMap().get("email alert"));
- }
-}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java
index 3983545140..cdbcf276d3 100644
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java
@@ -14,226 +14,67 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.alert.plugin;
-import org.apache.dolphinscheduler.alert.AlertServer;
-import org.apache.dolphinscheduler.alert.runner.AlertSender;
import org.apache.dolphinscheduler.alert.utils.Constants;
-import org.apache.dolphinscheduler.alert.utils.PropertyUtils;
-import org.apache.dolphinscheduler.common.enums.AlertStatus;
-import org.apache.dolphinscheduler.common.utils.JSONUtils;
-import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.DaoFactory;
-import org.apache.dolphinscheduler.dao.PluginDao;
-import org.apache.dolphinscheduler.dao.entity.Alert;
-import org.apache.dolphinscheduler.dao.entity.AlertGroup;
-import org.apache.dolphinscheduler.dao.entity.AlertPluginInstance;
-import org.apache.dolphinscheduler.dao.entity.PluginDefine;
-import org.apache.dolphinscheduler.spi.alert.AlertConstants;
-import org.apache.dolphinscheduler.spi.alert.ShowType;
-import org.apache.dolphinscheduler.spi.params.InputParam;
-import org.apache.dolphinscheduler.spi.params.PasswordParam;
-import org.apache.dolphinscheduler.spi.params.PluginParamsTransfer;
-import org.apache.dolphinscheduler.spi.params.RadioParam;
-import org.apache.dolphinscheduler.spi.params.base.DataType;
-import org.apache.dolphinscheduler.spi.params.base.ParamsOptions;
-import org.apache.dolphinscheduler.spi.params.base.PluginParams;
-import org.apache.dolphinscheduler.spi.params.base.Validate;
-import org.apache.dolphinscheduler.spi.utils.StringUtils;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.plugin.api.AlertPlugin;
+import org.apache.dolphinscheduler.plugin.model.AlertData;
+import org.apache.dolphinscheduler.plugin.model.AlertInfo;
+import org.apache.dolphinscheduler.plugin.model.PluginName;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.util.ArrayList;
-import java.util.Date;
-import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+import static org.junit.Assert.*;
-import com.google.common.collect.ImmutableList;
-
-/**
- * test load and use alert plugin
- */
public class EmailAlertPluginTest {
- AlertDao alertDao = DaoFactory.getDaoInstance(AlertDao.class);
- PluginDao pluginDao = DaoFactory.getDaoInstance(PluginDao.class);
-
- @Test
- @Ignore
- public void testRunSend() throws Exception {
-
- //create alert group
- AlertGroup alertGroup = new AlertGroup();
- alertGroup.setDescription("test alert group 1");
- alertGroup.setGroupName("testalertg1");
- alertDao.getAlertGroupMapper().insert(alertGroup);
-
- //add alert
- Alert alert1 = new Alert();
- alert1.setTitle("test alert");
- LinkedHashMap map1 = new LinkedHashMap<>();
- map1.put("mysql service name", "mysql200");
- map1.put("mysql address", "192.168.xx.xx");
- map1.put("port", "3306");
- map1.put(AlertConstants.SHOW_TYPE, ShowType.TEXT.getDescp());
- map1.put("no index of number", "80");
- map1.put("database client connections", "190");
-
- LinkedHashMap map2 = new LinkedHashMap<>();
- map2.put("mysql service name", "mysql210");
- map2.put("mysql address", "192.168.xx.xx");
- map2.put("port", "3306");
- map2.put("no index of number", "10");
- map1.put(AlertConstants.SHOW_TYPE, ShowType.TABLE.getDescp());
- map2.put("database client connections", "90");
-
- List> maps = new ArrayList<>();
- maps.add(0, map1);
- maps.add(1, map2);
- String mapjson = JSONUtils.toJsonString(maps);
- alert1.setContent(mapjson);
- alert1.setLog("log log");
- alert1.setAlertGroupId(alertGroup.getId());
- alertDao.addAlert(alert1);
-
- List alertList = new ArrayList<>();
- alertList.add(alert1);
-
- //load email alert plugin
- AlertPluginManager alertPluginManager = new AlertPluginManager();
- DolphinPluginManagerConfig alertPluginManagerConfig = new DolphinPluginManagerConfig();
- String path = DolphinPluginLoader.class.getClassLoader().getResource("").getPath();
- alertPluginManagerConfig.setPlugins(path + "../../../dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/pom.xml");
- if (StringUtils.isNotBlank(PropertyUtils.getString(AlertServer.ALERT_PLUGIN_DIR))) {
- alertPluginManagerConfig.setInstalledPluginsDir(PropertyUtils.getString(AlertServer.ALERT_PLUGIN_DIR, Constants.ALERT_PLUGIN_PATH).trim());
- }
-
- if (StringUtils.isNotBlank(PropertyUtils.getString(AlertServer.MAVEN_LOCAL_REPOSITORY))) {
- alertPluginManagerConfig.setMavenLocalRepository(PropertyUtils.getString(AlertServer.MAVEN_LOCAL_REPOSITORY).trim());
- }
-
- DolphinPluginLoader alertPluginLoader = new DolphinPluginLoader(alertPluginManagerConfig, ImmutableList.of(alertPluginManager));
- try {
- alertPluginLoader.loadPlugins();
- } catch (Exception e) {
- throw new RuntimeException("load Alert Plugin Failed !", e);
- }
-
- //create email alert plugin instance
- AlertPluginInstance alertPluginInstance = new AlertPluginInstance();
- alertPluginInstance.setCreateTime(new Date());
- alertPluginInstance.setInstanceName("test email alert");
-
- List pluginDefineList = pluginDao.getPluginDefineMapper().queryByNameAndType("email alert", "alert");
- if (pluginDefineList == null || pluginDefineList.size() == 0) {
- throw new RuntimeException("no alert plugin be load");
- }
- PluginDefine pluginDefine = pluginDefineList.get(0);
- alertPluginInstance.setPluginDefineId(pluginDefine.getId());
- alertPluginInstance.setPluginInstanceParams(getEmailAlertParams());
- alertDao.getAlertPluginInstanceMapper().insert(alertPluginInstance);
-
- AlertSender alertSender = new AlertSender(alertList, alertDao, alertPluginManager, pluginDao);
- alertSender.run();
+ private static final Logger logger = LoggerFactory.getLogger(EmailAlertPluginTest.class);
- Alert alertResult = alertDao.getAlertMapper().selectById(alert1.getId());
- Assert.assertNotNull(alertResult);
- Assert.assertEquals(alertResult.getAlertStatus(), AlertStatus.EXECUTION_FAILURE);
-
- alertDao.getAlertGroupMapper().deleteById(alertGroup.getId());
- alertDao.getAlertPluginInstanceMapper().deleteById(alertPluginInstance.getId());
- alertDao.getAlertMapper().deleteById(alert1.getId());
+ private AlertPlugin plugin;
+ @Before
+ public void before() {
+ plugin = new EmailAlertPlugin();
}
- public String getEmailAlertParams() {
-
- List paramsList = new ArrayList<>();
- InputParam receivesParam = InputParam.newBuilder("receivers", "receivers")
- .setValue("540957506@qq.com")
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .build();
-
- InputParam mailSmtpHost = InputParam.newBuilder("mailServerHost", "mail.smtp.host")
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue("smtp.exmail.qq.com")
- .build();
-
- InputParam mailSmtpPort = InputParam.newBuilder("mailServerPort", "mail.smtp.port")
- .addValidate(Validate.newBuilder()
- .setRequired(true)
- .setType(DataType.NUMBER.getDataType())
- .build())
- .setValue(25)
- .build();
-
- InputParam mailSender = InputParam.newBuilder("mailSender", "mail.sender")
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue("easyscheduler@analysys.com.cn")
- .build();
-
- RadioParam enableSmtpAuth = RadioParam.newBuilder("enableSmtpAuth", "mail.smtp.auth")
- .addParamsOptions(new ParamsOptions("YES", true, false))
- .addParamsOptions(new ParamsOptions("NO", false, false))
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue(true)
- .build();
-
- InputParam mailUser = InputParam.newBuilder("mailUser", "mail.user")
- .setPlaceholder("if enable use authentication, you need input user")
- .setValue("easyscheduler@analysys.com.cn")
- .build();
-
- PasswordParam mailPassword = PasswordParam.newBuilder("mailPasswd", "mail.passwd")
- .setPlaceholder("if enable use authentication, you need input password")
- .setValue("xxxxxxx")
- .build();
-
- RadioParam enableTls = RadioParam.newBuilder("starttlsEnable", "mail.smtp.starttls.enable")
- .addParamsOptions(new ParamsOptions("YES", true, false))
- .addParamsOptions(new ParamsOptions("NO", false, false))
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue(true)
- .build();
-
- RadioParam enableSsl = RadioParam.newBuilder("sslEnable", "mail.smtp.ssl.enable")
- .addParamsOptions(new ParamsOptions("YES", true, false))
- .addParamsOptions(new ParamsOptions("NO", false, false))
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue(false)
- .build();
-
- InputParam sslTrust = InputParam.newBuilder("mailSmtpSslTrust", "mail.smtp.ssl.trust")
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .setValue("smtp.exmail.qq.com")
- .build();
-
- List emailShowTypeList = new ArrayList<>();
- emailShowTypeList.add(new ParamsOptions(ShowType.TABLE.getDescp(), ShowType.TABLE.getDescp(), false));
- emailShowTypeList.add(new ParamsOptions(ShowType.TEXT.getDescp(), ShowType.TEXT.getDescp(), false));
- emailShowTypeList.add(new ParamsOptions(ShowType.ATTACHMENT.getDescp(), ShowType.ATTACHMENT.getDescp(), false));
- emailShowTypeList.add(new ParamsOptions(ShowType.TABLEATTACHMENT.getDescp(), ShowType.TABLEATTACHMENT.getDescp(), false));
- RadioParam showType = RadioParam.newBuilder(AlertConstants.SHOW_TYPE, "showType")
- .setParamsOptionsList(emailShowTypeList)
- .setValue(ShowType.TABLE.getDescp())
- .addValidate(Validate.newBuilder().setRequired(true).build())
- .build();
+ @Test
+ public void getId() {
+ String id = plugin.getId();
+ assertEquals(Constants.PLUGIN_DEFAULT_EMAIL_ID, id);
+ }
- paramsList.add(receivesParam);
- paramsList.add(mailSmtpHost);
- paramsList.add(mailSmtpPort);
- paramsList.add(mailSender);
- paramsList.add(enableSmtpAuth);
- paramsList.add(mailUser);
- paramsList.add(mailPassword);
- paramsList.add(enableTls);
- paramsList.add(enableSsl);
- paramsList.add(sslTrust);
- paramsList.add(showType);
+ @Test
+ public void getName() {
+ PluginName pluginName = plugin.getName();
+ assertEquals(Constants.PLUGIN_DEFAULT_EMAIL_CH, pluginName.getChinese());
+ assertEquals(Constants.PLUGIN_DEFAULT_EMAIL_EN, pluginName.getEnglish());
+ }
- return PluginParamsTransfer.transferParamsToJson(paramsList);
+ @Test
+ public void process() {
+ AlertInfo alertInfo = new AlertInfo();
+ AlertData alertData = new AlertData();
+ alertData.setId(1)
+ .setAlertGroupId(1)
+ .setContent("[\"alarm time:2018-02-05\", \"service name:MYSQL_ALTER\", \"alarm name:MYSQL_ALTER_DUMP\", " +
+ "\"get the alarm exception.!,interface error,exception information:timed out\", \"request address:http://blog.csdn.net/dreamInTheWorld/article/details/78539286\"]")
+ .setLog("test log")
+ .setReceivers("xx@xx.com")
+ .setReceiversCc("xx@xx.com")
+ .setShowType(ShowType.TEXT.getDescp())
+ .setTitle("test title");
+
+ alertInfo.setAlertData(alertData);
+ List list = new ArrayList(){{ add("xx@xx.com"); }};
+ alertInfo.addProp("receivers", list);
+// Map ret = plugin.process(alertInfo);
+// assertFalse(Boolean.parseBoolean(String.valueOf(ret.get(Constants.STATUS))));
}
-}
+}
\ No newline at end of file
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java
deleted file mode 100644
index 0126eb3dae..0000000000
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert.processor;
-
-import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
-import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.PluginDao;
-import org.apache.dolphinscheduler.remote.command.Command;
-import org.apache.dolphinscheduler.remote.command.CommandType;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendRequestCommand;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.powermock.api.mockito.PowerMockito;
-
-import io.netty.channel.Channel;
-
-/**
- * alert request processor test
- */
-public class AlertRequestProcessorTest {
-
- private AlertDao alertDao;
- private PluginDao pluginDao;
- private AlertPluginManager alertPluginManager;
-
- private AlertRequestProcessor alertRequestProcessor;
-
- @Before
- public void before() {
- alertDao = PowerMockito.mock(AlertDao.class);
- pluginDao = PowerMockito.mock(PluginDao.class);
- alertPluginManager = PowerMockito.mock(AlertPluginManager.class);
- alertRequestProcessor = new AlertRequestProcessor(alertDao,alertPluginManager,pluginDao);
- }
-
- @Test
- public void testProcess() {
- Channel channel = PowerMockito.mock(Channel.class);
- AlertSendRequestCommand alertSendRequestCommand = new AlertSendRequestCommand(1,"title","content");
- Command reqCommand = alertSendRequestCommand.convert2Command();
- Assert.assertEquals(CommandType.ALERT_SEND_REQUEST,reqCommand.getType());
- alertRequestProcessor.process(channel,reqCommand);
- }
-}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderTest.java
deleted file mode 100644
index 2664bdcd29..0000000000
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.alert.runner;
-
-import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
-import org.apache.dolphinscheduler.dao.AlertDao;
-import org.apache.dolphinscheduler.dao.PluginDao;
-import org.apache.dolphinscheduler.dao.entity.Alert;
-import org.apache.dolphinscheduler.dao.entity.AlertPluginInstance;
-import org.apache.dolphinscheduler.dao.entity.PluginDefine;
-import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseCommand;
-import org.apache.dolphinscheduler.spi.alert.AlertChannel;
-import org.apache.dolphinscheduler.spi.alert.AlertResult;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.powermock.api.mockito.PowerMockito;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * alert sender test
- */
-public class AlertSenderTest {
-
- private static final Logger logger = LoggerFactory.getLogger(AlertSenderTest.class);
-
- private AlertDao alertDao;
- private PluginDao pluginDao;
- private AlertPluginManager alertPluginManager;
-
- private AlertSender alertSender;
-
- @Before
- public void before() {
- alertDao = PowerMockito.mock(AlertDao.class);
- pluginDao = PowerMockito.mock(PluginDao.class);
- alertPluginManager = PowerMockito.mock(AlertPluginManager.class);
-
- }
-
- @Test
- public void testSyncHandler() {
-
- int alertGroupId = 1;
- String title = "alert mail test title";
- String content = "alert mail test content";
- alertSender = new AlertSender(alertDao,alertPluginManager,pluginDao);
-
- //1.alert instance does not exist
- PowerMockito.when(alertDao.listInstanceByAlertGroupId(alertGroupId)).thenReturn(null);
-
- AlertSendResponseCommand alertSendResponseCommand = alertSender.syncHandler(alertGroupId, title, content);
- Assert.assertFalse(alertSendResponseCommand.getResStatus());
- alertSendResponseCommand.getResResults().forEach(result ->
- logger.info("alert send response result, status:{}, message:{}",result.getStatus(),result.getMessage()));
-
- //2.alert plugin does not exist
- int pluginDefineId = 1;
- String pluginInstanceParams = "alert-instance-mail-params";
- String pluginInstanceName = "alert-instance-mail";
- List alertInstanceList = new ArrayList<>();
- AlertPluginInstance alertPluginInstance = new AlertPluginInstance(
- pluginDefineId,pluginInstanceParams,pluginInstanceName);
- alertInstanceList.add(alertPluginInstance);
- PowerMockito.when(alertDao.listInstanceByAlertGroupId(1)).thenReturn(alertInstanceList);
-
- String pluginName = "alert-plugin-mail";
- PluginDefine pluginDefine = new PluginDefine(pluginName,"1",null);
- PowerMockito.when(pluginDao.getPluginDefineById(pluginDefineId)).thenReturn(pluginDefine);
-
- alertSendResponseCommand = alertSender.syncHandler(alertGroupId, title, content);
- Assert.assertFalse(alertSendResponseCommand.getResStatus());
- alertSendResponseCommand.getResResults().forEach(result ->
- logger.info("alert send response result, status:{}, message:{}",result.getStatus(),result.getMessage()));
-
- //3.alert result value is null
- AlertChannel alertChannelMock = PowerMockito.mock(AlertChannel.class);
- PowerMockito.when(alertChannelMock.process(Mockito.any())).thenReturn(null);
- Map alertChannelMap = new ConcurrentHashMap<>();
- alertChannelMap.put(pluginName,alertChannelMock);
- PowerMockito.when(alertPluginManager.getAlertChannelMap()).thenReturn(alertChannelMap);
-
- alertSendResponseCommand = alertSender.syncHandler(alertGroupId, title, content);
- Assert.assertFalse(alertSendResponseCommand.getResStatus());
- alertSendResponseCommand.getResResults().forEach(result ->
- logger.info("alert send response result, status:{}, message:{}",result.getStatus(),result.getMessage()));
-
- //4.abnormal information inside the alert plug-in code
- AlertResult alertResult = new AlertResult();
- alertResult.setStatus(String.valueOf(false));
- alertResult.setMessage("Abnormal information inside the alert plug-in code");
- PowerMockito.when(alertChannelMock.process(Mockito.any())).thenReturn(alertResult);
- alertChannelMap = new ConcurrentHashMap<>();
- alertChannelMap.put(pluginName,alertChannelMock);
- PowerMockito.when(alertPluginManager.getAlertChannelMap()).thenReturn(alertChannelMap);
-
- alertSendResponseCommand = alertSender.syncHandler(alertGroupId, title, content);
- Assert.assertFalse(alertSendResponseCommand.getResStatus());
- alertSendResponseCommand.getResResults().forEach(result ->
- logger.info("alert send response result, status:{}, message:{}",result.getStatus(),result.getMessage()));
-
- //5.alert plugin send success
- alertResult = new AlertResult();
- alertResult.setStatus(String.valueOf(true));
- alertResult.setMessage(String.format("Alert Plugin %s send success",pluginInstanceName));
- PowerMockito.when(alertChannelMock.process(Mockito.any())).thenReturn(alertResult);
- alertChannelMap = new ConcurrentHashMap<>();
- alertChannelMap.put(pluginName,alertChannelMock);
- PowerMockito.when(alertPluginManager.getAlertChannelMap()).thenReturn(alertChannelMap);
-
- alertSendResponseCommand = alertSender.syncHandler(alertGroupId, title, content);
- Assert.assertTrue(alertSendResponseCommand.getResStatus());
- alertSendResponseCommand.getResResults().forEach(result ->
- logger.info("alert send response result, status:{}, message:{}",result.getStatus(),result.getMessage()));
-
- }
-
- @Test
- public void testRun() {
- int alertGroupId = 1;
- String title = "alert mail test title";
- String content = "alert mail test content";
- List alertList = new ArrayList<>();
- Alert alert = new Alert();
- alert.setAlertGroupId(alertGroupId);
- alert.setTitle(title);
- alert.setContent(content);
- alertList.add(alert);
-
- alertSender = new AlertSender(alertList,alertDao,alertPluginManager,pluginDao);
-
- int pluginDefineId = 1;
- String pluginInstanceParams = "alert-instance-mail-params";
- String pluginInstanceName = "alert-instance-mail";
- List alertInstanceList = new ArrayList<>();
- AlertPluginInstance alertPluginInstance = new AlertPluginInstance(
- pluginDefineId,pluginInstanceParams,pluginInstanceName);
- alertInstanceList.add(alertPluginInstance);
- PowerMockito.when(alertDao.listInstanceByAlertGroupId(alertGroupId)).thenReturn(alertInstanceList);
-
- String pluginName = "alert-plugin-mail";
- PluginDefine pluginDefine = new PluginDefine(pluginName,"1",null);
- PowerMockito.when(pluginDao.getPluginDefineById(pluginDefineId)).thenReturn(pluginDefine);
-
- AlertResult alertResult = new AlertResult();
- alertResult.setStatus(String.valueOf(true));
- alertResult.setMessage(String.format("Alert Plugin %s send success",pluginInstanceName));
- AlertChannel alertChannelMock = PowerMockito.mock(AlertChannel.class);
- PowerMockito.when(alertChannelMock.process(Mockito.any())).thenReturn(alertResult);
- ConcurrentHashMap alertChannelMap = new ConcurrentHashMap<>();
- alertChannelMap.put(pluginName,alertChannelMock);
- PowerMockito.when(alertPluginManager.getAlertChannelMap()).thenReturn(alertChannelMap);
- Assert.assertTrue(Boolean.parseBoolean(alertResult.getStatus()));
- alertSender.run();
-
- }
-
-}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactoryTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactoryTest.java
new file mode 100644
index 0000000000..32201e6011
--- /dev/null
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/AlertTemplateFactoryTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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.apache.dolphinscheduler.alert.template;
+
+import org.apache.dolphinscheduler.alert.template.impl.DefaultHTMLTemplate;
+import org.apache.dolphinscheduler.alert.utils.Constants;
+import org.apache.dolphinscheduler.alert.utils.PropertyUtils;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.mockito.Mockito.*;
+import static org.junit.Assert.*;
+
+/**
+ * test class for AlertTemplateFactory
+ */
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(PropertyUtils.class)
+public class AlertTemplateFactoryTest {
+
+ private static final Logger logger = LoggerFactory.getLogger(AlertTemplateFactoryTest.class);
+
+ /**
+ * GetMessageTemplate method test
+ */
+ @Test
+ public void testGetMessageTemplate(){
+
+ PowerMockito.mockStatic(PropertyUtils.class);
+
+ AlertTemplate defaultTemplate = AlertTemplateFactory.getMessageTemplate();
+
+ assertTrue(defaultTemplate instanceof DefaultHTMLTemplate);
+ }
+
+ /**
+ * GetMessageTemplate method throw Exception test
+ */
+ @Test
+ public void testGetMessageTemplateException(){
+
+ AlertTemplate defaultTemplate = AlertTemplateFactory.getMessageTemplate();
+ assertTrue(defaultTemplate instanceof DefaultHTMLTemplate);
+ }
+}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplateTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplateTest.java
new file mode 100644
index 0000000000..c88f69224d
--- /dev/null
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/template/impl/DefaultHTMLTemplateTest.java
@@ -0,0 +1,96 @@
+/*
+ * 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.apache.dolphinscheduler.alert.template.impl;
+
+import org.apache.dolphinscheduler.common.utils.*;
+import org.apache.dolphinscheduler.alert.utils.Constants;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+/**
+ * test class for DefaultHTMLTemplate
+ */
+public class DefaultHTMLTemplateTest{
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultHTMLTemplateTest.class);
+
+ /**
+ * only need test method GetMessageFromTemplate
+ */
+ @Test
+ public void testGetMessageFromTemplate(){
+
+ DefaultHTMLTemplate template = new DefaultHTMLTemplate();
+
+ String tableTypeMessage = template.getMessageFromTemplate(list2String(), ShowType.TABLE,true);
+
+ assertEquals(tableTypeMessage,generateMockTableTypeResultByHand());
+
+ String textTypeMessage = template.getMessageFromTemplate(list2String(), ShowType.TEXT,true);
+
+ assertEquals(textTypeMessage,generateMockTextTypeResultByHand());
+ }
+
+ /**
+ * generate some simulation data
+ */
+ private String list2String(){
+
+ LinkedHashMap map1 = new LinkedHashMap<>();
+ map1.put("mysql service name","mysql200");
+ map1.put("mysql address","192.168.xx.xx");
+ map1.put("database client connections","190");
+ map1.put("port","3306");
+ map1.put("no index of number","80");
+
+ LinkedHashMap map2 = new LinkedHashMap<>();
+ map2.put("mysql service name","mysql210");
+ map2.put("mysql address","192.168.xx.xx");
+ map2.put("database client connections","90");
+ map2.put("port","3306");
+ map2.put("no index of number","10");
+
+ List> maps = new ArrayList<>();
+ maps.add(0,map1);
+ maps.add(1,map2);
+ String mapjson = JSONUtils.toJsonString(maps);
+ logger.info(mapjson);
+
+ return mapjson;
+ }
+
+ private String generateMockTableTypeResultByHand(){
+
+ return Constants.HTML_HEADER_PREFIX +
+ "mysql service name | mysql address | database client connections | port | no index of number |
\n" +
+ "mysql200 | 192.168.xx.xx | 190 | 3306 | 80 |
mysql210 | 192.168.xx.xx | 90 | 3306 | 10 |
" + Constants.TABLE_BODY_HTML_TAIL;
+
+ }
+
+ private String generateMockTextTypeResultByHand(){
+
+ return Constants.HTML_HEADER_PREFIX + "{\"mysql service name\":\"mysql200\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"190\",\"port\":\"3306\",\"no index of number\":\"80\"} |
{\"mysql service name\":\"mysql210\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"90\",\"port\":\"3306\",\"no index of number\":\"10\"} |
" + Constants.TABLE_BODY_HTML_TAIL;
+ }
+}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtilsTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtilsTest.java
new file mode 100644
index 0000000000..ac62c17ea2
--- /dev/null
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/DingTalkUtilsTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+@PrepareForTest(PropertyUtils.class)
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore("javax.net.ssl.*")
+public class DingTalkUtilsTest {
+ Logger logger = LoggerFactory.getLogger(DingTalkUtilsTest.class);
+
+ private static final String mockUrl = "https://oapi.dingtalk.com/robot/send?access_token=test";
+ private static final String mockKeyWords = "onway";
+ private static final String msg = "ding talk test";
+
+ @Before
+ public void init(){
+ PowerMockito.mockStatic(PropertyUtils.class);
+ Mockito.when(PropertyUtils.getString(Constants.DINGTALK_WEBHOOK)).thenReturn(mockUrl);
+ Mockito.when(PropertyUtils.getString(Constants.DINGTALK_KEYWORD)).thenReturn(mockKeyWords);
+ Mockito.when(PropertyUtils.getBoolean(Constants.DINGTALK_PROXY_ENABLE)).thenReturn(true);
+ Mockito.when(PropertyUtils.getString(Constants.DINGTALK_PROXY)).thenReturn("proxy.com.cn");
+ Mockito.when(PropertyUtils.getString(Constants.DINGTALK_USER)).thenReturn("user");
+ Mockito.when(PropertyUtils.getString(Constants.DINGTALK_PASSWORD)).thenReturn("pswd");
+ Mockito.when(PropertyUtils.getInt(Constants.DINGTALK_PORT)).thenReturn(80);
+ }
+
+// @Test
+// @Ignore
+// public void testSendMsg() {
+// try {
+// String msgTosend = "msg to send";
+// logger.info(PropertyUtils.getString(Constants.DINGTALK_WEBHOOK));
+// String rsp = DingTalkUtils.sendDingTalkMsg(msgTosend, Constants.UTF_8);
+// logger.info("send msg result:{}",rsp);
+// String errmsg = JSONUtils.parseObject(rsp).getString("errmsg");
+// Assert.assertEquals("ok", errmsg);
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+
+ @Test
+ public void testCreateDefaultClient() {
+ CloseableHttpClient client = DingTalkUtils.getDefaultClient();;
+ try {
+ Assert.assertNotNull(client);
+ client.close();
+ } catch (IOException ex) {
+ logger.info("close exception",ex.getMessage());
+ new Throwable();
+ }
+ }
+ @Test
+ public void testCreateProxyClient() {
+ CloseableHttpClient client = DingTalkUtils.getProxyClient();
+ try {
+ Assert.assertNotNull(client);
+ client.close();
+ } catch (IOException ex) {
+ logger.info("close exception",ex.getMessage());
+ new Throwable();
+ }
+
+ }
+ @Test
+ public void testProxyConfig() {
+ RequestConfig rc = DingTalkUtils.getProxyConfig();
+ Assert.assertEquals(80, rc.getProxy().getPort());
+ Assert.assertEquals("proxy.com.cn", rc.getProxy().getHostName());
+ }
+
+ @Test
+ public void testDingTalkMsgToJson() {
+ String jsonString = DingTalkUtils.textToJsonString("this is test");
+
+ logger.info(jsonString);
+ String expect = "{\"text\":{\"content\":\"this is test\"},\"msgtype\":\"text\"}";
+ Assert.assertEquals(expect, jsonString);
+ }
+ @Test
+ public void testDingTalkMsgUtf8() {
+ String msg = DingTalkUtils.textToJsonString("this is test:中文");
+
+ logger.info("test support utf8, actual:" + msg);
+ logger.info("test support utf8, actual:" + DingTalkUtils.IS_ENABLE_DING_TALK);
+ String expect = "{\"text\":{\"content\":\"this is test:中文\"},\"msgtype\":\"text\"}";
+ Assert.assertEquals(expect, msg);
+ }
+
+}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtilsTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtilsTest.java
new file mode 100644
index 0000000000..1a70c5becb
--- /dev/null
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtilsTest.java
@@ -0,0 +1,283 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+import org.apache.dolphinscheduler.common.enums.AlertType;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.common.utils.JSONUtils;
+import org.apache.dolphinscheduler.dao.entity.Alert;
+import org.apache.dolphinscheduler.plugin.model.AlertData;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+/**
+ * Please manually modify the configuration file before testing.
+ * file: alert.properties
+ * enterprise.wechat.corp.id
+ * enterprise.wechat.secret
+ * enterprise.wechat.token.url
+ * enterprise.wechat.push.url
+ * enterprise.wechat.send.msg
+ * enterprise.wechat.agent.id
+ * enterprise.wechat.users
+ */
+@PrepareForTest(PropertyUtils.class)
+@RunWith(PowerMockRunner.class)
+public class EnterpriseWeChatUtilsTest {
+
+ private static final String toParty = "wwc99134b6fc1edb6";
+ private static final String enterpriseWechatSecret = "Uuv2KFrkdf7SeKOsTDCpsTkpawXBMNRhFy6VKX5FV";
+ private static final String enterpriseWechatAgentId = "1000004";
+ private static final String enterpriseWechatUsers = "LiGang,journey";
+ private static final String msg = "hello world";
+
+ private static final String enterpriseWechatTeamSendMsg = "{\\\"toparty\\\":\\\"{toParty}\\\",\\\"agentid\\\":\\\"{agentId}\\\""
+ +
+ ",\\\"msgtype\\\":\\\"text\\\",\\\"text\\\":{\\\"content\\\":\\\"{msg}\\\"},\\\"safe\\\":\\\"0\\\"}";
+ private static final String enterpriseWechatUserSendMsg = "{\\\"touser\\\":\\\"{toUser}\\\",\\\"agentid\\\":\\\"{agentId}\\\""
+ +
+ ",\\\"msgtype\\\":\\\"markdown\\\",\\\"markdown\\\":{\\\"content\\\":\\\"{msg}\\\"}}";
+
+ @Before
+ public void init() {
+ PowerMockito.mockStatic(PropertyUtils.class);
+ Mockito.when(PropertyUtils.getBoolean(Constants.ENTERPRISE_WECHAT_ENABLE)).thenReturn(true);
+ Mockito.when(PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_USER_SEND_MSG)).thenReturn(enterpriseWechatUserSendMsg);
+ Mockito.when(PropertyUtils.getString(Constants.ENTERPRISE_WECHAT_TEAM_SEND_MSG)).thenReturn(enterpriseWechatTeamSendMsg);
+ }
+
+ @Test
+ public void testIsEnable() {
+ Boolean weChartEnable = EnterpriseWeChatUtils.isEnable();
+ Assert.assertTrue(weChartEnable);
+ }
+
+ @Test
+ public void testMakeTeamSendMsg1() {
+ String sendMsg = EnterpriseWeChatUtils.makeTeamSendMsg(toParty, enterpriseWechatSecret, msg);
+ Assert.assertTrue(sendMsg.contains(toParty));
+ Assert.assertTrue(sendMsg.contains(enterpriseWechatSecret));
+ Assert.assertTrue(sendMsg.contains(msg));
+
+ }
+
+ @Test
+ public void testMakeTeamSendMsg2() {
+ List parties = new ArrayList<>();
+ parties.add(toParty);
+ parties.add("test1");
+
+ String sendMsg = EnterpriseWeChatUtils.makeTeamSendMsg(parties, enterpriseWechatSecret, msg);
+ Assert.assertTrue(sendMsg.contains(toParty));
+ Assert.assertTrue(sendMsg.contains(enterpriseWechatSecret));
+ Assert.assertTrue(sendMsg.contains(msg));
+ }
+
+ @Test
+ public void tesMakeUserSendMsg1() {
+
+ String sendMsg = EnterpriseWeChatUtils.makeUserSendMsg(enterpriseWechatUsers, enterpriseWechatAgentId, msg);
+ Assert.assertTrue(sendMsg.contains(enterpriseWechatUsers));
+ Assert.assertTrue(sendMsg.contains(enterpriseWechatAgentId));
+ Assert.assertTrue(sendMsg.contains(msg));
+ }
+
+ @Test
+ public void tesMakeUserSendMsg2() {
+ List users = new ArrayList<>();
+ users.add("user1");
+ users.add("user2");
+
+ String sendMsg = EnterpriseWeChatUtils.makeUserSendMsg(users, enterpriseWechatAgentId, msg);
+ Assert.assertTrue(sendMsg.contains(users.get(0)));
+ Assert.assertTrue(sendMsg.contains(users.get(1)));
+ Assert.assertTrue(sendMsg.contains(enterpriseWechatAgentId));
+ Assert.assertTrue(sendMsg.contains(msg));
+ }
+
+ @Test
+ public void testMarkdownByAlertForText() {
+ Alert alertForText = createAlertForText();
+ AlertData alertData = new AlertData();
+ alertData.setTitle(alertForText.getTitle())
+ .setShowType(alertForText.getShowType().getDescp())
+ .setContent(alertForText.getContent());
+ String result = EnterpriseWeChatUtils.markdownByAlert(alertData);
+ Assert.assertNotNull(result);
+ }
+
+ @Test
+ public void testMarkdownByAlertForTable() {
+ Alert alertForText = createAlertForTable();
+ AlertData alertData = new AlertData();
+ alertData.setTitle(alertForText.getTitle())
+ .setShowType(alertForText.getShowType().getDescp())
+ .setContent(alertForText.getContent());
+ String result = EnterpriseWeChatUtils.markdownByAlert(alertData);
+ Assert.assertNotNull(result);
+ }
+
+ private Alert createAlertForText() {
+ String content = "[{\"id\":\"69\","
+ +
+ "\"name\":\"UserBehavior-0--1193959466\","
+ +
+ "\"Job name\":\"Start workflow\","
+ +
+ "\"State\":\"SUCCESS\","
+ +
+ "\"Recovery\":\"NO\","
+ +
+ "\"Run time\":\"1\","
+ +
+ "\"Start time\": \"2018-08-06 10:31:34.0\","
+ +
+ "\"End time\": \"2018-08-06 10:31:49.0\","
+ +
+ "\"Host\": \"192.168.xx.xx\","
+ +
+ "\"Notify group\" :\"4\"}]";
+
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TEXT);
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(4);
+
+ return alert;
+ }
+
+ private String list2String() {
+
+ LinkedHashMap map1 = new LinkedHashMap<>();
+ map1.put("mysql service name", "mysql200");
+ map1.put("mysql address", "192.168.xx.xx");
+ map1.put("port", "3306");
+ map1.put("no index of number", "80");
+ map1.put("database client connections", "190");
+
+ LinkedHashMap map2 = new LinkedHashMap<>();
+ map2.put("mysql service name", "mysql210");
+ map2.put("mysql address", "192.168.xx.xx");
+ map2.put("port", "3306");
+ map2.put("no index of number", "10");
+ map2.put("database client connections", "90");
+
+ List> maps = new ArrayList<>();
+ maps.add(0, map1);
+ maps.add(1, map2);
+ String mapjson = JSONUtils.toJsonString(maps);
+ return mapjson;
+ }
+
+ private Alert createAlertForTable() {
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TABLE);
+ String content = list2String();
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ return alert;
+ }
+
+
+ // @Test
+ // public void testSendSingleTeamWeChat() {
+ // try {
+ // String token = EnterpriseWeChatUtils.getToken();
+ // String msg = EnterpriseWeChatUtils.makeTeamSendMsg(partyId, agentId, "hello world");
+ // String resp = EnterpriseWeChatUtils.sendEnterpriseWeChat("utf-8", msg, token);
+ //
+ // String errmsg = JSONUtils.parseObject(resp).getString("errmsg");
+ // Assert.assertEquals("ok",errmsg);
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // }
+ //
+ // @Test
+ // public void testSendMultiTeamWeChat() {
+ //
+ // try {
+ // String token = EnterpriseWeChatUtils.getToken();
+ // String msg = EnterpriseWeChatUtils.makeTeamSendMsg(listPartyId, agentId, "hello world");
+ // String resp = EnterpriseWeChatUtils.sendEnterpriseWeChat("utf-8", msg, token);
+ //
+ // String errmsg = JSONUtils.parseObject(resp).getString("errmsg");
+ // Assert.assertEquals("ok",errmsg);
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // }
+ //
+ // @Test
+ // public void testSendSingleUserWeChat() {
+ // try {
+ // String token = EnterpriseWeChatUtils.getToken();
+ // String msg = EnterpriseWeChatUtils.makeUserSendMsg(listUserId.stream().findFirst().get(), agentId, "your meeting room has been booked and will be synced to the 'mailbox' later \n" +
+ // ">**matter details** \n" +
+ // ">matter:meeting
" +
+ // ">organizer:@miglioguan \n" +
+ // ">participant:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang \n" +
+ // "> \n" +
+ // ">meeting room:Guangzhou TIT 1st Floor 301 \n" +
+ // ">date:May 18, 2018 \n" +
+ // ">time:9:00-11:00 am \n" +
+ // "> \n" +
+ // ">please attend the meeting on time\n" +
+ // "> \n" +
+ // ">to modify the meeting information, please click: [Modify Meeting Information](https://work.weixin.qq.com)\"");
+ //
+ // String resp = EnterpriseWeChatUtils.sendEnterpriseWeChat("utf-8", msg, token);
+ //
+ // String errmsg = JSONUtils.parseObject(resp).getString("errmsg");
+ // Assert.assertEquals("ok",errmsg);
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // }
+ //
+ // @Test
+ // public void testSendMultiUserWeChat() {
+ // try {
+ // String token = EnterpriseWeChatUtils.getToken();
+ //
+ // String msg = EnterpriseWeChatUtils.makeUserSendMsg(listUserId, agentId, "hello world");
+ // String resp = EnterpriseWeChatUtils.sendEnterpriseWeChat("utf-8", msg, token);
+ //
+ // String errmsg = JSONUtils.parseObject(resp).getString("errmsg");
+ // Assert.assertEquals("ok",errmsg);
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // }
+
+}
diff --git a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/ExcelUtilsTest.java
similarity index 89%
rename from dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java
rename to dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/ExcelUtilsTest.java
index 5c8b195176..c4833252b2 100644
--- a/dolphinscheduler-alert-plugin/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/ExcelUtilsTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.dolphinscheduler.plugin.alert.email;
+package org.apache.dolphinscheduler.alert.utils;
import static org.junit.Assert.assertTrue;
@@ -63,7 +63,7 @@ public class ExcelUtilsTest {
//Define dest file path
String xlsFilePath = rootPath + System.getProperty("file.separator");
- logger.info("xlsFilePath: " + xlsFilePath);
+ logger.info("XLS_FILE_PATH: " + xlsFilePath);
//Define correctContent
String correctContent = "[{\"name\":\"ds name\",\"value\":\"ds value\"}]";
@@ -78,7 +78,7 @@ public class ExcelUtilsTest {
ExcelUtils.genExcelFile(correctContent, title, xlsFilePath);
//Test file exists
- File xlsFile = new File(xlsFilePath + EmailConstants.SINGLE_SLASH + title + EmailConstants.EXCEL_SUFFIX_XLS);
+ File xlsFile = new File(xlsFilePath + Constants.SINGLE_SLASH + title + Constants.EXCEL_SUFFIX_XLS);
assertTrue(xlsFile.exists());
//Expected RuntimeException
@@ -98,7 +98,7 @@ public class ExcelUtilsTest {
@Test
public void testGenExcelFileByCheckDir() {
ExcelUtils.genExcelFile("[{\"a\": \"a\"},{\"a\": \"a\"}]", "t", "/tmp/xls");
- File file = new File("/tmp/xls" + EmailConstants.SINGLE_SLASH + "t" + EmailConstants.EXCEL_SUFFIX_XLS);
+ File file = new File("/tmp/xls" + Constants.SINGLE_SLASH + "t" + Constants.EXCEL_SUFFIX_XLS);
file.delete();
}
-}
\ No newline at end of file
+}
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/FuncUtilsTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/FuncUtilsTest.java
index 818fac98b6..a4aeea9c0c 100644
--- a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/FuncUtilsTest.java
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/FuncUtilsTest.java
@@ -17,15 +17,15 @@
package org.apache.dolphinscheduler.alert.utils;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.util.Arrays;
-
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
public class FuncUtilsTest {
private static final Logger logger = LoggerFactory.getLogger(FuncUtilsTest.class);
diff --git a/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/MailUtilsTest.java b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/MailUtilsTest.java
new file mode 100644
index 0000000000..26a69c43ba
--- /dev/null
+++ b/dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/MailUtilsTest.java
@@ -0,0 +1,190 @@
+/*
+ * 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.apache.dolphinscheduler.alert.utils;
+
+
+import org.apache.dolphinscheduler.common.enums.AlertType;
+import org.apache.dolphinscheduler.common.enums.ShowType;
+import org.apache.dolphinscheduler.dao.AlertDao;
+import org.apache.dolphinscheduler.dao.DaoFactory;
+import org.apache.dolphinscheduler.dao.entity.Alert;
+import org.apache.dolphinscheduler.dao.entity.User;
+import org.junit.Assert;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+import org.apache.dolphinscheduler.common.utils.*;
+
+
+/**
+ */
+public class MailUtilsTest {
+ private static final Logger logger = LoggerFactory.getLogger(MailUtilsTest.class);
+ @Test
+ public void testSendMails() {
+ String[] receivers = new String[]{"347801120@qq.com"};
+ String[] receiversCc = new String[]{"347801120@qq.com"};
+
+ String content ="[\"id:69\"," +
+ "\"name:UserBehavior-0--1193959466\"," +
+ "\"Job name: Start workflow\"," +
+ "\"State: SUCCESS\"," +
+ "\"Recovery:NO\"," +
+ "\"Run time: 1\"," +
+ "\"Start time: 2018-08-06 10:31:34.0\"," +
+ "\"End time: 2018-08-06 10:31:49.0\"," +
+ "\"Host: 192.168.xx.xx\"," +
+ "\"Notify group :4\"]";
+
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TEXT);
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(4);
+
+ MailUtils.sendMails(Arrays.asList(receivers),Arrays.asList(receiversCc),alert.getTitle(),alert.getContent(), ShowType.TEXT.getDescp());
+ }
+
+
+ @Test
+ public void testQuery(){
+ AlertDao alertDao = DaoFactory.getDaoInstance(AlertDao.class);
+ List alerts = alertDao.listWaitExecutionAlert();
+
+ String[] mails = new String[]{"xx@xx.com"};
+
+ for(Alert alert : alerts){
+ MailUtils.sendMails(Arrays.asList(mails),"gaojing", alert.getContent(), ShowType.TABLE.getDescp());
+ }
+
+ }
+
+ public String list2String(){
+
+ LinkedHashMap map1 = new LinkedHashMap<>();
+ map1.put("mysql service name","mysql200");
+ map1.put("mysql address","192.168.xx.xx");
+ map1.put("port","3306");
+ map1.put("no index of number","80");
+ map1.put("database client connections","190");
+
+ LinkedHashMap map2 = new LinkedHashMap<>();
+ map2.put("mysql service name","mysql210");
+ map2.put("mysql address","192.168.xx.xx");
+ map2.put("port","3306");
+ map2.put("no index of number","10");
+ map2.put("database client connections","90");
+
+ List> maps = new ArrayList<>();
+ maps.add(0,map1);
+ maps.add(1,map2);
+ String mapjson = JSONUtils.toJsonString(maps);
+ logger.info(mapjson);
+
+ return mapjson;
+
+ }
+
+ @Test
+ public void testSendTableMail(){
+ String[] mails = new String[]{"347801120@qq.com"};
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TABLE);
+ String content= list2String();
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ MailUtils.sendMails(Arrays.asList(mails),"gaojing", alert.getContent(), ShowType.TABLE.getDescp());
+ }
+
+ /**
+ * Used to test add alarm information, mail sent
+ * Text
+ */
+ @Test
+ public void addAlertText(){
+ AlertDao alertDao = DaoFactory.getDaoInstance(AlertDao.class);
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TEXT);
+ alert.setContent("[\"alarm time:2018-02-05\", \"service name:MYSQL_ALTER\", \"alarm name:MYSQL_ALTER_DUMP\", " +
+ "\"get the alarm exception.!,interface error,exception information:timed out\", \"request address:http://blog.csdn.net/dreamInTheWorld/article/details/78539286\"]");
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ alertDao.addAlert(alert);
+ }
+
+
+ /**
+ * Used to test add alarm information, mail sent
+ * Table
+ */
+ @Test
+ public void testAddAlertTable(){
+ logger.info("testAddAlertTable");
+ AlertDao alertDao = DaoFactory.getDaoInstance(AlertDao.class);
+ Assert.assertNotNull(alertDao);
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TABLE);
+
+ String content = list2String();
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ alertDao.addAlert(alert);
+ logger.info("" +alert);
+ }
+
+ @Test
+ public void testAlertDao(){
+ AlertDao alertDao = DaoFactory.getDaoInstance(AlertDao.class);
+ List users = alertDao.listUserByAlertgroupId(3);
+ logger.info(users.toString());
+ }
+
+ @Test
+ public void testAttachmentFile()throws Exception{
+ String[] mails = new String[]{"xx@xx.com"};
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.ATTACHMENT);
+ String content = list2String();
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ MailUtils.sendMails(Arrays.asList(mails),"gaojing",alert.getContent(),ShowType.ATTACHMENT.getDescp());
+ }
+
+ @Test
+ public void testTableAttachmentFile()throws Exception{
+ String[] mails = new String[]{"xx@xx.com"};
+ Alert alert = new Alert();
+ alert.setTitle("Mysql Exception");
+ alert.setShowType(ShowType.TABLEATTACHMENT);
+ String content = list2String();
+ alert.setContent(content);
+ alert.setAlertType(AlertType.EMAIL);
+ alert.setAlertGroupId(1);
+ MailUtils.sendMails(Arrays.asList(mails),"gaojing",alert.getContent(),ShowType.TABLEATTACHMENT.getDescp());
+ }
+
+}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertGroupController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertGroupController.java
index 10590529bf..37c38d6b6c 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertGroupController.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertGroupController.java
@@ -14,45 +14,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.api.controller;
-import static org.apache.dolphinscheduler.api.enums.Status.CREATE_ALERT_GROUP_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.DELETE_ALERT_GROUP_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.LIST_PAGING_ALERT_GROUP_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.QUERY_ALL_ALERTGROUP_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.UPDATE_ALERT_GROUP_ERROR;
-
-import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.exceptions.ApiException;
import org.apache.dolphinscheduler.api.service.AlertGroupService;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
+import org.apache.dolphinscheduler.common.enums.AlertType;
import org.apache.dolphinscheduler.common.utils.ParameterUtils;
-import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestController;
-
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
+import org.apache.dolphinscheduler.api.enums.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.apache.dolphinscheduler.api.enums.Status.*;
+
/**
* alert group controller
*/
@@ -70,31 +57,28 @@ public class AlertGroupController extends BaseController {
/**
* create alert group
*
- * @param loginUser login user
- * @param groupName group name
+ * @param loginUser login user
+ * @param groupName group name
+ * @param groupType group type
* @param description description
* @return create result code
*/
@ApiOperation(value = "createAlertgroup", notes = "CREATE_ALERT_GROUP_NOTES")
@ApiImplicitParams({
@ApiImplicitParam(name = "groupName", value = "GROUP_NAME", required = true, dataType = "String"),
- @ApiImplicitParam(name = "description", value = "DESC", dataType = "String"),
- @ApiImplicitParam(name = "alertInstanceIds", value = "alertInstanceIds", dataType = "String")
+ @ApiImplicitParam(name = "groupType", value = "GROUP_TYPE", required = true, dataType = "AlertType"),
+ @ApiImplicitParam(name = "description", value = "DESC", dataType = "String")
})
@PostMapping(value = "/create")
@ResponseStatus(HttpStatus.CREATED)
@ApiException(CREATE_ALERT_GROUP_ERROR)
public Result createAlertgroup(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@RequestParam(value = "groupName") String groupName,
- @RequestParam(value = "description", required = false) String description,
- @RequestParam(value = "alertInstanceIds") String alertInstanceIds) {
- String strUserName = StringUtils.replaceNRTtoUnderline(loginUser.getUserName());
- String strGroupName = StringUtils.replaceNRTtoUnderline(groupName);
- String strDescription = StringUtils.replaceNRTtoUnderline(description);
- String strAlertInstanceIds = StringUtils.replaceNRTtoUnderline(alertInstanceIds);
- logger.info("loginUser user {}, create alert group, groupName: {}, desc: {},alertInstanceIds:{}",
- strUserName, strGroupName, strDescription, strAlertInstanceIds);
- Map result = alertGroupService.createAlertgroup(loginUser, groupName, description, alertInstanceIds);
+ @RequestParam(value = "groupType") AlertType groupType,
+ @RequestParam(value = "description", required = false) String description) {
+ logger.info("loginUser user {}, create alertgroup, groupName: {}, groupType: {}, desc: {}",
+ loginUser.getUserName(), groupName, groupType, description);
+ Map result = alertGroupService.createAlertgroup(loginUser, groupName, groupType, description);
return returnDataList(result);
}
@@ -119,9 +103,9 @@ public class AlertGroupController extends BaseController {
* paging query alarm group list
*
* @param loginUser login user
- * @param pageNo page number
+ * @param pageNo page number
* @param searchVal search value
- * @param pageSize page size
+ * @param pageSize page size
* @return alert group list page
*/
@ApiOperation(value = "queryAlertGroupListPaging", notes = "QUERY_ALERT_GROUP_LIST_PAGING_NOTES")
@@ -152,9 +136,10 @@ public class AlertGroupController extends BaseController {
/**
* updateProcessInstance alert group
*
- * @param loginUser login user
- * @param id alert group id
- * @param groupName group name
+ * @param loginUser login user
+ * @param id alert group id
+ * @param groupName group name
+ * @param groupType group type
* @param description description
* @return update result code
*/
@@ -162,8 +147,8 @@ public class AlertGroupController extends BaseController {
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "ALERT_GROUP_ID", required = true, dataType = "Int", example = "100"),
@ApiImplicitParam(name = "groupName", value = "GROUP_NAME", required = true, dataType = "String"),
- @ApiImplicitParam(name = "description", value = "DESC", dataType = "String"),
- @ApiImplicitParam(name = "alertInstanceIds", value = "alertInstanceIds", dataType = "String")
+ @ApiImplicitParam(name = "groupType", value = "GROUP_TYPE", required = true, dataType = "AlertType"),
+ @ApiImplicitParam(name = "description", value = "DESC", dataType = "String")
})
@PostMapping(value = "/update")
@ResponseStatus(HttpStatus.OK)
@@ -171,13 +156,11 @@ public class AlertGroupController extends BaseController {
public Result updateAlertgroup(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@RequestParam(value = "id") int id,
@RequestParam(value = "groupName") String groupName,
- @RequestParam(value = "description", required = false) String description,
- @RequestParam(value = "alertInstanceIds") String alertInstanceIds) {
- logger.info("login user {}, updateProcessInstance alert group, groupName: {}, desc: {}",
- StringUtils.replaceNRTtoUnderline(loginUser.getUserName()),
- StringUtils.replaceNRTtoUnderline(groupName),
- StringUtils.replaceNRTtoUnderline(description));
- Map result = alertGroupService.updateAlertgroup(loginUser, id, groupName, description, alertInstanceIds);
+ @RequestParam(value = "groupType") AlertType groupType,
+ @RequestParam(value = "description", required = false) String description) {
+ logger.info("login user {}, updateProcessInstance alertgroup, groupName: {}, groupType: {}, desc: {}",
+ loginUser.getUserName(), groupName, groupType, description);
+ Map result = alertGroupService.updateAlertgroup(loginUser, id, groupName, groupType, description);
return returnDataList(result);
}
@@ -185,7 +168,7 @@ public class AlertGroupController extends BaseController {
* delete alert group by id
*
* @param loginUser login user
- * @param id alert group id
+ * @param id alert group id
* @return delete result code
*/
@ApiOperation(value = "delAlertgroupById", notes = "DELETE_ALERT_GROUP_BY_ID_NOTES")
@@ -232,4 +215,28 @@ public class AlertGroupController extends BaseController {
}
return result;
}
+
+ /**
+ * grant user
+ *
+ * @param loginUser login user
+ * @param userIds user ids in the group
+ * @param alertgroupId alert group id
+ * @return grant result code
+ */
+ @ApiOperation(value = "grantUser", notes = "GRANT_ALERT_GROUP_NOTES")
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", value = "ALERT_GROUP_ID", required = true, dataType = "Int", example = "100"),
+ @ApiImplicitParam(name = "userIds", value = "USER_IDS", required = true, dataType = "String")
+ })
+ @PostMapping(value = "/grant-user")
+ @ResponseStatus(HttpStatus.OK)
+ @ApiException(ALERT_GROUP_GRANT_USER_ERROR)
+ public Result grantUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
+ @RequestParam(value = "alertgroupId") int alertgroupId,
+ @RequestParam(value = "userIds") String userIds) {
+ logger.info("login user {}, grant user, alertGroupId: {},userIds : {}", loginUser.getUserName(), alertgroupId, userIds);
+ Map result = alertGroupService.grantUser(loginUser, alertgroupId, userIds);
+ return returnDataList(result);
+ }
}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceController.java
deleted file mode 100644
index d34f42060f..0000000000
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceController.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.api.controller;
-
-import static org.apache.dolphinscheduler.api.enums.Status.CREATE_ALERT_PLUGIN_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.DELETE_ALERT_PLUGIN_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.GET_ALERT_PLUGIN_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.LIST_PAGING_ALERT_PLUGIN_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.QUERY_ALL_ALERT_PLUGIN_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.UPDATE_ALERT_PLUGIN_INSTANCE_ERROR;
-
-import org.apache.dolphinscheduler.api.enums.Status;
-import org.apache.dolphinscheduler.api.exceptions.ApiException;
-import org.apache.dolphinscheduler.api.service.AlertPluginInstanceService;
-import org.apache.dolphinscheduler.api.utils.Result;
-import org.apache.dolphinscheduler.common.Constants;
-import org.apache.dolphinscheduler.common.utils.StringUtils;
-import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import springfox.documentation.annotations.ApiIgnore;
-
-/**
- * alert plugin instance controller
- */
-@Api(tags = "ALERT_PLUGIN_INSTANCE_TAG", position = 1)
-@RestController
-@RequestMapping("alert-plugin-instance")
-public class AlertPluginInstanceController extends BaseController {
-
- private static final Logger logger = LoggerFactory.getLogger(AlertPluginInstanceController.class);
-
- @Autowired
- private AlertPluginInstanceService alertPluginInstanceService;
-
-
- /**
- * create alert plugin instance
- *
- * @param loginUser login user
- * @param pluginDefineId alert plugin define id
- * @param instanceName instance name
- * @param pluginInstanceParams instance params
- * @return result
- */
- @ApiOperation(value = "createAlertPluginInstance", notes = "CREATE_ALERT_PLUGIN_INSTANCE_NOTES")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "pluginDefineId", value = "ALERT_PLUGIN_DEFINE_ID", required = true, dataType = "Int", example = "100"),
- @ApiImplicitParam(name = "instanceName", value = "ALERT_PLUGIN_INSTANCE_NAME", required = true, dataType = "String", example = "DING TALK"),
- @ApiImplicitParam(name = "pluginInstanceParams", value = "ALERT_PLUGIN_INSTANCE_PARAMS", required = true, dataType = "String", example = "ALERT_PLUGIN_INSTANCE_PARAMS")
- })
- @PostMapping(value = "/create")
- @ResponseStatus(HttpStatus.CREATED)
- @ApiException(CREATE_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result createAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "pluginDefineId") int pluginDefineId,
- @RequestParam(value = "instanceName") String instanceName,
- @RequestParam(value = "pluginInstanceParams") String pluginInstanceParams) {
- logger.info("login user {},create alert plugin instance, instanceName:{} ",
- StringUtils.replaceNRTtoUnderline(loginUser.getUserName()),
- StringUtils.replaceNRTtoUnderline(instanceName));
- Map result = alertPluginInstanceService.create(loginUser, pluginDefineId, instanceName, pluginInstanceParams);
- return returnDataList(result);
- }
-
- /**
- * updateAlertPluginInstance
- *
- * @param loginUser login user
- * @param alertPluginInstanceId alert plugin instance id
- * @param instanceName instance name
- * @param pluginInstanceParams instance params
- * @return result
- */
- @ApiOperation(value = "update", notes = "UPDATE_ALERT_PLUGIN_INSTANCE_NOTES")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "alertPluginInstanceId", value = "ALERT_PLUGIN_INSTANCE_ID", required = true, dataType = "Int", example = "100"),
- @ApiImplicitParam(name = "instanceName", value = "ALERT_PLUGIN_INSTANCE_NAME", required = true, dataType = "String", example = "DING TALK"),
- @ApiImplicitParam(name = "pluginInstanceParams", value = "ALERT_PLUGIN_INSTANCE_PARAMS", required = true, dataType = "String", example = "ALERT_PLUGIN_INSTANCE_PARAMS")
- })
- @GetMapping(value = "/update")
- @ResponseStatus(HttpStatus.OK)
- @ApiException(UPDATE_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result updateAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "alertPluginInstanceId") int alertPluginInstanceId,
- @RequestParam(value = "instanceName") String instanceName,
- @RequestParam(value = "pluginInstanceParams") String pluginInstanceParams) {
- logger.info("login user {},update alert plugin instance id {}", StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), alertPluginInstanceId);
- Map result = alertPluginInstanceService.update(loginUser, alertPluginInstanceId, instanceName, pluginInstanceParams);
- return returnDataList(result);
- }
-
- /**
- * deleteAlertPluginInstance
- *
- * @param loginUser login user
- * @param id id
- * @return result
- */
- @ApiOperation(value = "delete", notes = "DELETE_ALERT_PLUGIN_INSTANCE_NOTES")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", value = "ALERT_PLUGIN_ID", required = true, dataType = "Int", example = "100")
- })
- @GetMapping(value = "/delete")
- @ResponseStatus(HttpStatus.OK)
- @ApiException(DELETE_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result deleteAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "id") int id) {
- logger.info("login user {},delete alert plugin instance id {}", StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), id);
-
- Map result = alertPluginInstanceService.delete(loginUser, id);
- return returnDataList(result);
- }
-
- /**
- * getAlertPluginInstance
- *
- * @param loginUser login user
- * @param id alert plugin instance id
- * @return result
- */
- @ApiOperation(value = "get", notes = "GET_ALERT_PLUGIN_INSTANCE_NOTES")
- @PostMapping(value = "/get")
- @ResponseStatus(HttpStatus.OK)
- @ApiException(GET_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result getAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "id") int id) {
- logger.info("login user {},get alert plugin instance, id {}", StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), id);
- Map result = alertPluginInstanceService.get(loginUser, id);
- return returnDataList(result);
- }
-
- /**
- * getAlertPluginInstance
- *
- * @param loginUser login user
- * @return result
- */
- @ApiOperation(value = "/queryAll", notes = "QUERY_ALL_ALERT_PLUGIN_INSTANCE_NOTES")
- @PostMapping(value = "/queryAll")
- @ResponseStatus(HttpStatus.OK)
- @ApiException(QUERY_ALL_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result getAlertPluginInstance(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser) {
- logger.info("login user {}, query all alert plugin instance", StringUtils.replaceNRTtoUnderline(loginUser.getUserName()));
- Map result = alertPluginInstanceService.queryAll();
- return returnDataList(result);
- }
-
- /**
- * check alert group exist
- *
- * @param loginUser login user
- * @param alertInstanceName alert instance name
- * @return check result code
- */
- @ApiOperation(value = "verifyAlertInstanceName", notes = "VERIFY_ALERT_INSTANCE_NAME_NOTES")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "groupName", value = "GROUP_NAME", required = true, dataType = "String"),
- })
- @GetMapping(value = "/verify-alert-instance-name")
- @ResponseStatus(HttpStatus.OK)
- public Result verifyGroupName(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "alertInstanceName") String alertInstanceName) {
- logger.info("login user {},verify alert instance name: {}", StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), StringUtils.replaceNRTtoUnderline(alertInstanceName));
-
- boolean exist = alertPluginInstanceService.checkExistPluginInstanceName(alertInstanceName);
- Result result = new Result();
- if (exist) {
- logger.error("alert plugin instance {} has exist, can't create again.", alertInstanceName);
- result.setCode(Status.PLUGIN_INSTANCE_ALREADY_EXIT.getCode());
- result.setMsg(Status.PLUGIN_INSTANCE_ALREADY_EXIT.getMsg());
- } else {
- result.setCode(Status.SUCCESS.getCode());
- result.setMsg(Status.SUCCESS.getMsg());
- }
- return result;
- }
-
- /**
- * paging query alert plugin instance group list
- *
- * @param loginUser login user
- * @param pageNo page number
- * @param pageSize page size
- * @return alert plugin instance list page
- */
- @ApiOperation(value = "queryAlertPluginInstanceListPaging", notes = "QUERY_ALERT_PLUGIN_INSTANCE_LIST_PAGING_NOTES")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "pageNo", value = "PAGE_NO", dataType = "Int", example = "1"),
- @ApiImplicitParam(name = "pageSize", value = "PAGE_SIZE", dataType = "Int", example = "20")
- })
- @GetMapping(value = "/list-paging")
- @ResponseStatus(HttpStatus.OK)
- @ApiException(LIST_PAGING_ALERT_PLUGIN_INSTANCE_ERROR)
- public Result listPaging(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam("pageNo") Integer pageNo,
- @RequestParam("pageSize") Integer pageSize) {
- logger.info("login user {}, list paging, pageNo: {}, pageSize: {}",StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), pageNo, pageSize);
- Map result = checkPageParams(pageNo, pageSize);
- if (result.get(Constants.STATUS) != Status.SUCCESS) {
- return returnDataListPaging(result);
- }
-
- result = alertPluginInstanceService.queryPluginPage(pageNo, pageSize);
- return returnDataListPaging(result);
- }
-
-}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/ExecutorController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/ExecutorController.java
index c1e75a73f5..b093483df1 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/ExecutorController.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/ExecutorController.java
@@ -14,49 +14,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.api.controller;
-import static org.apache.dolphinscheduler.api.enums.Status.CHECK_PROCESS_DEFINITION_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.EXECUTE_PROCESS_INSTANCE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.START_PROCESS_INSTANCE_ERROR;
import org.apache.dolphinscheduler.api.enums.ExecuteType;
import org.apache.dolphinscheduler.api.exceptions.ApiException;
import org.apache.dolphinscheduler.api.service.ExecutorService;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
-import org.apache.dolphinscheduler.common.enums.CommandType;
-import org.apache.dolphinscheduler.common.enums.FailureStrategy;
-import org.apache.dolphinscheduler.common.enums.Priority;
-import org.apache.dolphinscheduler.common.enums.RunMode;
-import org.apache.dolphinscheduler.common.enums.TaskDependType;
-import org.apache.dolphinscheduler.common.enums.WarningType;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.text.ParseException;
-import java.util.Map;
-
+import io.swagger.annotations.*;
+import org.apache.dolphinscheduler.common.enums.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
+import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
+import java.text.ParseException;
+import java.util.Map;
+
+import static org.apache.dolphinscheduler.api.enums.Status.*;
+
+
/**
* execute process controller
*/
@@ -73,20 +55,22 @@ public class ExecutorController extends BaseController {
/**
* execute process instance
*
- * @param loginUser login user
- * @param projectName project name
- * @param processDefinitionId process definition id
- * @param scheduleTime schedule time
- * @param failureStrategy failure strategy
- * @param startNodeList start nodes list
- * @param taskDependType task depend type
- * @param execType execute type
- * @param warningType warning type
- * @param warningGroupId warning group id
- * @param runMode run mode
+ * @param loginUser login user
+ * @param projectName project name
+ * @param processDefinitionId process definition id
+ * @param scheduleTime schedule time
+ * @param failureStrategy failure strategy
+ * @param startNodeList start nodes list
+ * @param taskDependType task depend type
+ * @param execType execute type
+ * @param warningType warning type
+ * @param warningGroupId warning group id
+ * @param receivers receivers
+ * @param receiversCc receivers cc
+ * @param runMode run mode
* @param processInstancePriority process instance priority
- * @param workerGroup worker group
- * @param timeout timeout
+ * @param workerGroup worker group
+ * @param timeout timeout
* @return start process result code
*/
@ApiOperation(value = "startProcessInstance", notes = "RUN_PROCESS_INSTANCE_NOTES")
@@ -99,6 +83,8 @@ public class ExecutorController extends BaseController {
@ApiImplicitParam(name = "execType", value = "COMMAND_TYPE", dataType = "CommandType"),
@ApiImplicitParam(name = "warningType", value = "WARNING_TYPE", required = true, dataType = "WarningType"),
@ApiImplicitParam(name = "warningGroupId", value = "WARNING_GROUP_ID", required = true, dataType = "Int", example = "100"),
+ @ApiImplicitParam(name = "receivers", value = "RECEIVERS", dataType = "String"),
+ @ApiImplicitParam(name = "receiversCc", value = "RECEIVERS_CC", dataType = "String"),
@ApiImplicitParam(name = "runMode", value = "RUN_MODE", dataType = "RunMode"),
@ApiImplicitParam(name = "processInstancePriority", value = "PROCESS_INSTANCE_PRIORITY", required = true, dataType = "Priority"),
@ApiImplicitParam(name = "workerGroup", value = "WORKER_GROUP", dataType = "String", example = "default"),
@@ -117,16 +103,19 @@ public class ExecutorController extends BaseController {
@RequestParam(value = "execType", required = false) CommandType execType,
@RequestParam(value = "warningType", required = true) WarningType warningType,
@RequestParam(value = "warningGroupId", required = false) int warningGroupId,
+ @RequestParam(value = "receivers", required = false) String receivers,
+ @RequestParam(value = "receiversCc", required = false) String receiversCc,
@RequestParam(value = "runMode", required = false) RunMode runMode,
@RequestParam(value = "processInstancePriority", required = false) Priority processInstancePriority,
@RequestParam(value = "workerGroup", required = false, defaultValue = "default") String workerGroup,
@RequestParam(value = "timeout", required = false) Integer timeout,
@RequestParam(value = "startParams", required = false) String startParams) throws ParseException {
- logger.info("login user {}, start process instance, project name: {}, process definition id: {}, schedule time: {}, "
+ logger.info("login user {}, start process instance, project name: {}, process definition id: {}, schedule time: {}, "
+ "failure policy: {}, node name: {}, node dep: {}, notify type: {}, "
- + "notify group id: {}, run mode: {},process instance priority:{}, workerGroup: {}, timeout: {}, startParams: {} ",
+ + "notify group id: {},receivers:{},receiversCc:{}, run mode: {},process instance priority:{}, workerGroup: {}, timeout: {}, "
+ + "startParams: {}",
loginUser.getUserName(), projectName, processDefinitionId, scheduleTime,
- failureStrategy, startNodeList, taskDependType, warningType, workerGroup, runMode, processInstancePriority,
+ failureStrategy, startNodeList, taskDependType, warningType, workerGroup, receivers, receiversCc, runMode, processInstancePriority,
workerGroup, timeout, startParams);
if (timeout == null) {
@@ -138,7 +127,7 @@ public class ExecutorController extends BaseController {
}
Map result = execService.execProcessInstance(loginUser, projectName, processDefinitionId, scheduleTime, execType, failureStrategy,
startNodeList, taskDependType, warningType,
- warningGroupId, runMode, processInstancePriority, workerGroup, timeout, startParamMap);
+ warningGroupId, receivers, receiversCc, runMode, processInstancePriority, workerGroup, timeout, startParamMap);
return returnDataList(result);
}
@@ -146,10 +135,10 @@ public class ExecutorController extends BaseController {
/**
* do action to process instance:pause, stop, repeat, recover from pause, recover from stop
*
- * @param loginUser login user
- * @param projectName project name
+ * @param loginUser login user
+ * @param projectName project name
* @param processInstanceId process instance id
- * @param executeType execute type
+ * @param executeType execute type
* @return execute result code
*/
@ApiOperation(value = "execute", notes = "EXECUTE_ACTION_TO_PROCESS_INSTANCE_NOTES")
@@ -174,7 +163,7 @@ public class ExecutorController extends BaseController {
/**
* check process definition and all of the son process definitions is on line.
*
- * @param loginUser login user
+ * @param loginUser login user
* @param processDefinitionId process definition id
* @return check result code
*/
@@ -191,4 +180,32 @@ public class ExecutorController extends BaseController {
Map result = execService.startCheckByProcessDefinedId(processDefinitionId);
return returnDataList(result);
}
+
+ /**
+ * query recipients and copyers by process definition ID
+ *
+ * @param loginUser login user
+ * @param processDefinitionId process definition id
+ * @param processInstanceId process instance id
+ * @return receivers cc list
+ */
+ @ApiIgnore
+ @ApiOperation(value = "getReceiverCc", notes = "GET_RECEIVER_CC_NOTES")
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "processDefinitionId", value = "PROCESS_DEFINITION_ID", required = true, dataType = "Int", example = "100"),
+ @ApiImplicitParam(name = "processInstanceId", value = "PROCESS_INSTANCE_ID", required = true, dataType = "Int", example = "100")
+
+ })
+ @GetMapping(value = "/get-receiver-cc")
+ @ResponseStatus(HttpStatus.OK)
+ @ApiException(QUERY_RECIPIENTS_AND_COPYERS_BY_PROCESS_DEFINITION_ERROR)
+ public Result getReceiverCc(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
+ @RequestParam(value = "processDefinitionId", required = false) Integer processDefinitionId,
+ @RequestParam(value = "processInstanceId", required = false) Integer processInstanceId) {
+ logger.info("login user {}, get process definition receiver and cc", loginUser.getUserName());
+ Map result = execService.getReceiverCc(processDefinitionId, processInstanceId);
+ return returnDataList(result);
+ }
+
+
}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/SchedulerController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/SchedulerController.java
index ca57ad11a4..5713d7ffc4 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/SchedulerController.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/SchedulerController.java
@@ -14,18 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.api.controller;
-import static org.apache.dolphinscheduler.api.enums.Status.CREATE_SCHEDULE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.DELETE_SCHEDULE_CRON_BY_ID_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.OFFLINE_SCHEDULE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.PREVIEW_SCHEDULE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.PUBLISH_SCHEDULE_ONLINE_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.QUERY_SCHEDULE_LIST_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.QUERY_SCHEDULE_LIST_PAGING_ERROR;
-import static org.apache.dolphinscheduler.api.enums.Status.UPDATE_SCHEDULE_ERROR;
-import static org.apache.dolphinscheduler.common.Constants.SESSION_USER;
import org.apache.dolphinscheduler.api.exceptions.ApiException;
import org.apache.dolphinscheduler.api.service.SchedulerService;
@@ -35,31 +25,21 @@ import org.apache.dolphinscheduler.common.enums.Priority;
import org.apache.dolphinscheduler.common.enums.ReleaseState;
import org.apache.dolphinscheduler.common.enums.WarningType;
import org.apache.dolphinscheduler.common.utils.ParameterUtils;
-import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.util.Map;
-
+import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
+import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
+import java.io.IOException;
+import java.util.Map;
+
+import static org.apache.dolphinscheduler.api.enums.Status.*;
+import static org.apache.dolphinscheduler.common.Constants.SESSION_USER;
+
/**
* schedule controller
*/
@@ -81,15 +61,17 @@ public class SchedulerController extends BaseController {
/**
* create schedule
*
- * @param loginUser login user
- * @param projectName project name
- * @param processDefinitionId process definition id
- * @param schedule scheduler
- * @param warningType warning type
- * @param warningGroupId warning group id
- * @param failureStrategy failure strategy
+ * @param loginUser login user
+ * @param projectName project name
+ * @param processDefinitionId process definition id
+ * @param schedule scheduler
+ * @param warningType warning type
+ * @param warningGroupId warning group id
+ * @param failureStrategy failure strategy
* @param processInstancePriority process instance priority
- * @param workerGroup worker group
+ * @param receivers receivers
+ * @param receiversCc receivers cc
+ * @param workerGroup worker group
* @return create result code
*/
@ApiOperation(value = "createSchedule", notes = "CREATE_SCHEDULE_NOTES")
@@ -99,6 +81,8 @@ public class SchedulerController extends BaseController {
@ApiImplicitParam(name = "warningType", value = "WARNING_TYPE", type = "WarningType"),
@ApiImplicitParam(name = "warningGroupId", value = "WARNING_GROUP_ID", dataType = "Int", example = "100"),
@ApiImplicitParam(name = "failureStrategy", value = "FAILURE_STRATEGY", type = "FailureStrategy"),
+ @ApiImplicitParam(name = "receivers", value = "RECEIVERS", type = "String"),
+ @ApiImplicitParam(name = "receiversCc", value = "RECEIVERS_CC", type = "String"),
@ApiImplicitParam(name = "workerGroupId", value = "WORKER_GROUP_ID", dataType = "Int", example = "100"),
@ApiImplicitParam(name = "processInstancePriority", value = "PROCESS_INSTANCE_PRIORITY", type = "Priority"),
})
@@ -112,14 +96,16 @@ public class SchedulerController extends BaseController {
@RequestParam(value = "warningType", required = false, defaultValue = DEFAULT_WARNING_TYPE) WarningType warningType,
@RequestParam(value = "warningGroupId", required = false, defaultValue = DEFAULT_NOTIFY_GROUP_ID) int warningGroupId,
@RequestParam(value = "failureStrategy", required = false, defaultValue = DEFAULT_FAILURE_POLICY) FailureStrategy failureStrategy,
+ @RequestParam(value = "receivers", required = false) String receivers,
+ @RequestParam(value = "receiversCc", required = false) String receiversCc,
@RequestParam(value = "workerGroup", required = false, defaultValue = "default") String workerGroup,
- @RequestParam(value = "processInstancePriority", required = false, defaultValue = DEFAULT_PROCESS_INSTANCE_PRIORITY) Priority processInstancePriority) {
- logger.info("login user {},project name: {}, process name: {}, create schedule: {}, warning type: {}, warning group id: {},"
- + "failure policy: {},processInstancePriority : {}, workGroupId:{}",
- StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), StringUtils.replaceNRTtoUnderline(projectName), processDefinitionId, schedule, warningType, warningGroupId,
- failureStrategy, processInstancePriority, workerGroup);
+ @RequestParam(value = "processInstancePriority", required = false, defaultValue = DEFAULT_PROCESS_INSTANCE_PRIORITY) Priority processInstancePriority) throws IOException {
+ logger.info("login user {}, project name: {}, process name: {}, create schedule: {}, warning type: {}, warning group id: {}," +
+ "failure policy: {},receivers : {},receiversCc : {},processInstancePriority : {}, workGroupId:{}",
+ loginUser.getUserName(), projectName, processDefinitionId, schedule, warningType, warningGroupId,
+ failureStrategy, receivers, receiversCc, processInstancePriority, workerGroup);
Map result = schedulerService.insertSchedule(loginUser, projectName, processDefinitionId, schedule,
- warningType, warningGroupId, failureStrategy, processInstancePriority, workerGroup);
+ warningType, warningGroupId, failureStrategy, receivers, receiversCc, processInstancePriority, workerGroup);
return returnDataList(result);
}
@@ -127,15 +113,17 @@ public class SchedulerController extends BaseController {
/**
* updateProcessInstance schedule
*
- * @param loginUser login user
- * @param projectName project name
- * @param id scheduler id
- * @param schedule scheduler
- * @param warningType warning type
- * @param warningGroupId warning group id
- * @param failureStrategy failure strategy
- * @param workerGroup worker group
+ * @param loginUser login user
+ * @param projectName project name
+ * @param id scheduler id
+ * @param schedule scheduler
+ * @param warningType warning type
+ * @param warningGroupId warning group id
+ * @param failureStrategy failure strategy
+ * @param receivers receivers
+ * @param workerGroup worker group
* @param processInstancePriority process instance priority
+ * @param receiversCc receivers cc
* @return update result code
*/
@ApiOperation(value = "updateSchedule", notes = "UPDATE_SCHEDULE_NOTES")
@@ -145,6 +133,8 @@ public class SchedulerController extends BaseController {
@ApiImplicitParam(name = "warningType", value = "WARNING_TYPE", type = "WarningType"),
@ApiImplicitParam(name = "warningGroupId", value = "WARNING_GROUP_ID", dataType = "Int", example = "100"),
@ApiImplicitParam(name = "failureStrategy", value = "FAILURE_STRATEGY", type = "FailureStrategy"),
+ @ApiImplicitParam(name = "receivers", value = "RECEIVERS", type = "String"),
+ @ApiImplicitParam(name = "receiversCc", value = "RECEIVERS_CC", type = "String"),
@ApiImplicitParam(name = "workerGroupId", value = "WORKER_GROUP_ID", dataType = "Int", example = "100"),
@ApiImplicitParam(name = "processInstancePriority", value = "PROCESS_INSTANCE_PRIORITY", type = "Priority"),
})
@@ -157,24 +147,26 @@ public class SchedulerController extends BaseController {
@RequestParam(value = "warningType", required = false, defaultValue = DEFAULT_WARNING_TYPE) WarningType warningType,
@RequestParam(value = "warningGroupId", required = false) int warningGroupId,
@RequestParam(value = "failureStrategy", required = false, defaultValue = "END") FailureStrategy failureStrategy,
+ @RequestParam(value = "receivers", required = false) String receivers,
+ @RequestParam(value = "receiversCc", required = false) String receiversCc,
@RequestParam(value = "workerGroup", required = false, defaultValue = "default") String workerGroup,
- @RequestParam(value = "processInstancePriority", required = false) Priority processInstancePriority) {
- logger.info("login user {},project name: {},id: {}, updateProcessInstance schedule: {}, notify type: {}, notify mails: {}, "
- + "failure policy: {},processInstancePriority : {},workerGroupId:{}",
- StringUtils.replaceNRTtoUnderline(loginUser.getUserName()), StringUtils.replaceNRTtoUnderline(projectName), id, schedule, warningType, warningGroupId, failureStrategy,
- processInstancePriority, workerGroup);
+ @RequestParam(value = "processInstancePriority", required = false) Priority processInstancePriority) throws IOException {
+ logger.info("login user {}, project name: {},id: {}, updateProcessInstance schedule: {}, notify type: {}, notify mails: {}, " +
+ "failure policy: {},receivers : {},receiversCc : {},processInstancePriority : {},workerGroupId:{}",
+ loginUser.getUserName(), projectName, id, schedule, warningType, warningGroupId, failureStrategy,
+ receivers, receiversCc, processInstancePriority, workerGroup);
Map result = schedulerService.updateSchedule(loginUser, projectName, id, schedule,
- warningType, warningGroupId, failureStrategy, null, processInstancePriority, workerGroup);
+ warningType, warningGroupId, failureStrategy, receivers, receiversCc, null, processInstancePriority, workerGroup);
return returnDataList(result);
}
/**
* publish schedule setScheduleState
*
- * @param loginUser login user
+ * @param loginUser login user
* @param projectName project name
- * @param id scheduler id
+ * @param id scheduler id
* @return publish result code
*/
@ApiOperation(value = "online", notes = "ONLINE_SCHEDULE_NOTES")
@@ -195,9 +187,9 @@ public class SchedulerController extends BaseController {
/**
* offline schedule
*
- * @param loginUser login user
+ * @param loginUser login user
* @param projectName project name
- * @param id schedule id
+ * @param id schedule id
* @return operation result code
*/
@ApiOperation(value = "offline", notes = "OFFLINE_SCHEDULE_NOTES")
@@ -219,12 +211,12 @@ public class SchedulerController extends BaseController {
/**
* query schedule list paging
*
- * @param loginUser login user
- * @param projectName project name
+ * @param loginUser login user
+ * @param projectName project name
* @param processDefinitionId process definition id
- * @param pageNo page number
- * @param pageSize page size
- * @param searchVal search value
+ * @param pageNo page number
+ * @param pageSize page size
+ * @param searchVal search value
* @return schedule list page
*/
@ApiOperation(value = "queryScheduleListPaging", notes = "QUERY_SCHEDULE_LIST_PAGING_NOTES")
@@ -253,9 +245,9 @@ public class SchedulerController extends BaseController {
/**
* delete schedule by id
*
- * @param loginUser login user
+ * @param loginUser login user
* @param projectName project name
- * @param scheduleId scheule id
+ * @param scheduleId scheule id
* @return delete result code
*/
@ApiOperation(value = "deleteScheduleById", notes = "OFFLINE_SCHEDULE_NOTES")
@@ -278,7 +270,7 @@ public class SchedulerController extends BaseController {
/**
* query schedule list
*
- * @param loginUser login user
+ * @param loginUser login user
* @param projectName project name
* @return schedule list
*/
@@ -296,9 +288,9 @@ public class SchedulerController extends BaseController {
/**
* preview schedule
*
- * @param loginUser login user
+ * @param loginUser login user
* @param projectName project name
- * @param schedule schedule expression
+ * @param schedule schedule expression
* @return the next five fire time
*/
@ApiOperation(value = "previewSchedule", notes = "PREVIEW_SCHEDULE_NOTES")
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UiPluginController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UiPluginController.java
deleted file mode 100644
index 3589bdcdc0..0000000000
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UiPluginController.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.api.controller;
-
-import static org.apache.dolphinscheduler.api.enums.Status.QUERY_PLUGINS_ERROR;
-
-import org.apache.dolphinscheduler.api.exceptions.ApiException;
-import org.apache.dolphinscheduler.api.service.UiPluginService;
-import org.apache.dolphinscheduler.api.utils.Result;
-import org.apache.dolphinscheduler.common.Constants;
-import org.apache.dolphinscheduler.common.enums.PluginType;
-import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseStatus;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import springfox.documentation.annotations.ApiIgnore;
-
-/**
- * UiPluginController
- * Some plugins (such as alert plugin) need to provide UI interfaces to users.
- * We use from-creat to dynamically generate UI interfaces. Related parameters are mainly provided by pluginParams.
- * From-create can generate dynamic ui based on this parameter.
- */
-@Api(tags = "UI_PLUGINS", position = 1)
-@RestController
-@RequestMapping("ui-plugins")
-public class UiPluginController extends BaseController {
-
- private static final Logger logger = LoggerFactory.getLogger(UiPluginController.class);
-
- @Autowired
- UiPluginService uiPluginService;
-
- @ApiOperation(value = "queryUiPluginsByType", notes = "QUERY_UI_PLUGINS_BY_TYPE")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "pluginType", value = "pluginType", required = true, dataType = "PluginType"),
- })
- @PostMapping(value = "/queryUiPluginsByType")
- @ResponseStatus(HttpStatus.CREATED)
- @ApiException(QUERY_PLUGINS_ERROR)
- public Result queryUiPluginsByType(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "pluginType") PluginType pluginType) {
-
- logger.info("query plugins by type , pluginType: {}", pluginType);
- Map result = uiPluginService.queryUiPluginsByType(pluginType);
- return returnDataList(result);
- }
-
- @ApiOperation(value = "queryUiPluginDetailById", notes = "QUERY_UI_PLUGIN_DETAIL_BY_ID")
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "PluginType"),
- })
- @PostMapping(value = "/queryUiPluginDetailById")
- @ResponseStatus(HttpStatus.CREATED)
- @ApiException(QUERY_PLUGINS_ERROR)
- public Result queryUiPluginDetailById(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam("pluginId") Integer pluginId) {
-
- logger.info("query plugin detail by id , pluginId: {}", pluginId);
- Map result = uiPluginService.queryUiPluginDetailById(pluginId);
- return returnDataList(result);
- }
-}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java
index 04ef02303d..c56f7d0b95 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java
@@ -276,28 +276,13 @@ public enum Status {
QUEUE_COUNT_ERROR(90001, "queue count error", "查询队列数据错误"),
KERBEROS_STARTUP_STATE(100001, "get kerberos startup state error", "获取kerberos启动状态错误"),
-
- //plugin
- PLUGIN_NOT_A_UI_COMPONENT(110001, "query plugin error, this plugin has no UI component", "查询插件错误,此插件无UI组件"),
- QUERY_PLUGINS_RESULT_IS_NULL(110002, "query plugins result is null", "查询插件为空"),
- QUERY_PLUGINS_ERROR(110003, "query plugins error", "查询插件错误"),
- QUERY_PLUGIN_DETAIL_RESULT_IS_NULL(110004, "query plugin detail result is null", "查询插件详情结果为空"),
-
- UPDATE_ALERT_PLUGIN_INSTANCE_ERROR(110005, "update alert plugin instance error", "更新告警组和告警组插件实例错误"),
- DELETE_ALERT_PLUGIN_INSTANCE_ERROR(110006, "delete alert plugin instance error", "删除告警组和告警组插件实例错误"),
- GET_ALERT_PLUGIN_INSTANCE_ERROR(110007, "get alert plugin instance error", "获取告警组和告警组插件实例错误"),
- CREATE_ALERT_PLUGIN_INSTANCE_ERROR(110008, "create alert plugin instance error", "创建告警组和告警组插件实例错误"),
- QUERY_ALL_ALERT_PLUGIN_INSTANCE_ERROR(110009, "query all alert plugin instance error", "查询所有告警实例失败"),
- PLUGIN_INSTANCE_ALREADY_EXIT(110010,"plugin instance already exit","该告警插件实例已存在"),
- LIST_PAGING_ALERT_PLUGIN_INSTANCE_ERROR(110011,"query plugin instance page error","分页查询告警实例失败"),
-
;
private final int code;
private final String enMsg;
private final String zhMsg;
- Status(int code, String enMsg, String zhMsg) {
+ private Status(int code, String enMsg, String zhMsg) {
this.code = code;
this.enMsg = enMsg;
this.zhMsg = zhMsg;
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertGroupService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertGroupService.java
index e1e63a623c..e9a90d5903 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertGroupService.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertGroupService.java
@@ -14,9 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.api.service;
+import java.util.*;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.common.Constants;
@@ -25,33 +25,29 @@ import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.AlertGroup;
import org.apache.dolphinscheduler.dao.entity.User;
+import org.apache.dolphinscheduler.dao.entity.UserAlertGroup;
import org.apache.dolphinscheduler.dao.mapper.AlertGroupMapper;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-
/**
* alert group service
*/
@Service
-public class AlertGroupService extends BaseService {
+public class AlertGroupService extends BaseService{
private static final Logger logger = LoggerFactory.getLogger(AlertGroupService.class);
@Autowired
private AlertGroupMapper alertGroupMapper;
+ @Autowired
+ private UserAlertGroupService userAlertGroupService;
/**
* query alert group list
*
@@ -85,7 +81,7 @@ public class AlertGroupService extends BaseService {
Page page = new Page(pageNo, pageSize);
IPage alertGroupIPage = alertGroupMapper.queryAlertGroupPage(
- page, searchVal);
+ page, searchVal);
PageInfo pageInfo = new PageInfo<>(pageNo, pageSize);
pageInfo.setTotalCount((int) alertGroupIPage.getTotal());
pageInfo.setLists(alertGroupIPage.getRecords());
@@ -100,11 +96,11 @@ public class AlertGroupService extends BaseService {
*
* @param loginUser login user
* @param groupName group name
+ * @param groupType group type
* @param desc description
- * @param alertInstanceIds alertInstanceIds
* @return create result code
*/
- public Map createAlertgroup(User loginUser, String groupName, String desc, String alertInstanceIds) {
+ public Map createAlertgroup(User loginUser, String groupName, AlertType groupType, String desc) {
Map result = new HashMap<>();
//only admin can operate
if (isNotAdmin(loginUser, result)) {
@@ -115,11 +111,10 @@ public class AlertGroupService extends BaseService {
Date now = new Date();
alertGroup.setGroupName(groupName);
- alertGroup.setAlertInstanceIds(alertInstanceIds);
+ alertGroup.setGroupType(groupType);
alertGroup.setDescription(desc);
alertGroup.setCreateTime(now);
alertGroup.setUpdateTime(now);
- alertGroup.setCreateUserId(loginUser.getId());
// insert
int insert = alertGroupMapper.insert(alertGroup);
@@ -138,17 +133,18 @@ public class AlertGroupService extends BaseService {
* @param loginUser login user
* @param id alert group id
* @param groupName group name
+ * @param groupType group type
* @param desc description
- * @param alertInstanceIds alertInstanceIds
* @return update result code
*/
- public Map updateAlertgroup(User loginUser, int id, String groupName, String desc, String alertInstanceIds) {
+ public Map updateAlertgroup(User loginUser, int id, String groupName, AlertType groupType, String desc) {
Map result = new HashMap<>();
if (isNotAdmin(loginUser, result)) {
return result;
}
+
AlertGroup alertGroup = alertGroupMapper.selectById(id);
if (alertGroup == null) {
@@ -162,10 +158,12 @@ public class AlertGroupService extends BaseService {
if (StringUtils.isNotEmpty(groupName)) {
alertGroup.setGroupName(groupName);
}
+
+ if (groupType != null) {
+ alertGroup.setGroupType(groupType);
+ }
alertGroup.setDescription(desc);
alertGroup.setUpdateTime(now);
- alertGroup.setCreateUserId(loginUser.getId());
- alertGroup.setAlertInstanceIds(alertInstanceIds);
// updateProcessInstance
alertGroupMapper.updateById(alertGroup);
putMsg(result, Status.SUCCESS);
@@ -194,11 +192,57 @@ public class AlertGroupService extends BaseService {
putMsg(result, Status.ALERT_GROUP_NOT_EXIST);
return result;
}
+
+ userAlertGroupService.deleteByAlertGroupId(id);
alertGroupMapper.deleteById(id);
putMsg(result, Status.SUCCESS);
return result;
}
+
+ /**
+ * grant user
+ *
+ * @param loginUser login user
+ * @param alertgroupId alert group id
+ * @param userIds user id list
+ * @return grant result code
+ */
+ public Map grantUser(User loginUser, int alertgroupId, String userIds) {
+ Map result = new HashMap<>();
+ result.put(Constants.STATUS, false);
+
+ //only admin can operate
+ if (isNotAdmin(loginUser, result)) {
+ return result;
+ }
+
+ userAlertGroupService.deleteByAlertGroupId(alertgroupId);
+ if (StringUtils.isEmpty(userIds)) {
+ putMsg(result, Status.SUCCESS);
+ return result;
+ }
+
+ String[] userIdsArr = userIds.split(",");
+ Date now = new Date();
+ List alertGroups = new ArrayList<>(userIds.length());
+ for (String userId : userIdsArr) {
+ UserAlertGroup userAlertGroup = new UserAlertGroup();
+ userAlertGroup.setAlertgroupId(alertgroupId);
+ userAlertGroup.setUserId(Integer.parseInt(userId));
+ userAlertGroup.setCreateTime(now);
+ userAlertGroup.setUpdateTime(now);
+ alertGroups.add(userAlertGroup);
+ }
+
+ if (CollectionUtils.isNotEmpty(alertGroups)) {
+ userAlertGroupService.saveBatch(alertGroups);
+ }
+
+ putMsg(result, Status.SUCCESS);
+ return result;
+ }
+
/**
* verify group name exists
*
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceService.java
deleted file mode 100644
index d526a41d99..0000000000
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceService.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.apache.dolphinscheduler.api.service;
-
-import org.apache.dolphinscheduler.dao.entity.User;
-
-import java.util.Map;
-
-/**
- * alert plugin instance service
- */
-public interface AlertPluginInstanceService {
-
- /**
- * creat alert plugin instance
- *
- * @param loginUser login user
- * @param pluginDefineId plugin define id
- * @param instanceName instance name
- * @param pluginInstanceParams plugin instance params
- * @return result
- */
- Map create(User loginUser,int pluginDefineId,String instanceName,String pluginInstanceParams);
-
- /**
- * update
- * @param loginUser login user
- * @param alertPluginInstanceId plugin instance id
- * @param instanceName instance name
- * @param pluginInstanceParams plugin instance params
- * @return result
- */
- Map update(User loginUser, int alertPluginInstanceId,String instanceName,String pluginInstanceParams);
-
- /**
- * delete alert plugin instance
- *
- * @param loginUser login user
- * @param id id
- * @return result
- */
- Map delete(User loginUser, int id);
-
- /**
- * get alert plugin instance
- *
- * @param loginUser login user
- * @param id get id
- * @return alert plugin
- */
- Map get(User loginUser, int id);
-
- /**
- * queryAll
- *
- * @return alert plugins
- */
- Map queryAll();
-
- /**
- * checkExistPluginInstanceName
- * @param pluginName plugin name
- * @return isExist
- */
- boolean checkExistPluginInstanceName(String pluginName);
-
- /**
- * queryPluginPage
- * @param pageIndex page index
- * @param pageSize page size
- * @return plugins
- */
- Map queryPluginPage(int pageIndex,int pageSize);
-}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ExecutorService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ExecutorService.java
index 77be0a048c..f53d9026f9 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ExecutorService.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ExecutorService.java
@@ -107,6 +107,8 @@ public class ExecutorService extends BaseService {
* @param taskDependType node dependency type
* @param warningType warning type
* @param warningGroupId notify group id
+ * @param receivers receivers
+ * @param receiversCc receivers cc
* @param processInstancePriority process instance priority
* @param workerGroup worker group name
* @param runMode run mode
@@ -119,7 +121,7 @@ public class ExecutorService extends BaseService {
int processDefinitionId, String cronTime, CommandType commandType,
FailureStrategy failureStrategy, String startNodeList,
TaskDependType taskDependType, WarningType warningType, int warningGroupId,
- RunMode runMode,
+ String receivers, String receiversCc, RunMode runMode,
Priority processInstancePriority, String workerGroup, Integer timeout,
Map startParams) throws ParseException {
Map result = new HashMap<>();
@@ -159,9 +161,12 @@ public class ExecutorService extends BaseService {
int create = this.createCommand(commandType, processDefinitionId,
taskDependType, failureStrategy, startNodeList, cronTime, warningType, loginUser.getId(),
warningGroupId, runMode, processInstancePriority, workerGroup, startParams);
-
if (create > 0) {
- processDefinition.setWarningGroupId(warningGroupId);
+ /**
+ * according to the process definition ID updateProcessInstance and CC recipient
+ */
+ processDefinition.setReceivers(receivers);
+ processDefinition.setReceiversCc(receiversCc);
processDefinitionMapper.updateById(processDefinition);
putMsg(result, Status.SUCCESS);
} else {
@@ -443,6 +448,42 @@ public class ExecutorService extends BaseService {
return result;
}
+ /**
+ * query recipients and copyers by process definition id or processInstanceId
+ *
+ * @param processDefineId process definition id
+ * @param processInstanceId process instance id
+ * @return receivers cc list
+ */
+ public Map getReceiverCc(Integer processDefineId, Integer processInstanceId) {
+ Map result = new HashMap<>();
+ logger.info("processInstanceId {}", processInstanceId);
+ if (processDefineId == null && processInstanceId == null) {
+ throw new RuntimeException("You must set values for parameters processDefineId or processInstanceId");
+ }
+ if (processDefineId == null && processInstanceId != null) {
+ ProcessInstance processInstance = processInstanceMapper.selectById(processInstanceId);
+ if (processInstance == null) {
+ throw new RuntimeException("processInstanceId is not exists");
+ }
+ processDefineId = processInstance.getProcessDefinitionId();
+ }
+ ProcessDefinition processDefinition = processDefinitionMapper.selectById(processDefineId);
+ if (processDefinition == null) {
+ throw new RuntimeException(String.format("processDefineId %d is not exists", processDefineId));
+ }
+
+ String receivers = processDefinition.getReceivers();
+ String receiversCc = processDefinition.getReceiversCc();
+ Map dataMap = new HashMap<>();
+ dataMap.put(Constants.RECEIVERS, receivers);
+ dataMap.put(Constants.RECEIVERS_CC, receiversCc);
+
+ result.put(Constants.DATA_LIST, dataMap);
+ putMsg(result, Status.SUCCESS);
+ return result;
+ }
+
/**
* create command
*
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessInstanceService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessInstanceService.java
index 1d6169b06e..3f55fae66f 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessInstanceService.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessInstanceService.java
@@ -189,7 +189,8 @@ public class ProcessInstanceService extends BaseService {
ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
ProcessDefinition processDefinition = processService.findProcessDefineById(processInstance.getProcessDefinitionId());
- processInstance.setWarningGroupId(processDefinition.getWarningGroupId());
+ processInstance.setReceivers(processDefinition.getReceivers());
+ processInstance.setReceiversCc(processDefinition.getReceiversCc());
result.put(DATA_LIST, processInstance);
putMsg(result, Status.SUCCESS);
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/SchedulerService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/SchedulerService.java
index 55880ad63c..93fa14872a 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/SchedulerService.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/SchedulerService.java
@@ -14,22 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.dolphinscheduler.api.service;
+
import org.apache.dolphinscheduler.api.dto.ScheduleParam;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.exceptions.ServiceException;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.common.Constants;
-import org.apache.dolphinscheduler.common.enums.FailureStrategy;
-import org.apache.dolphinscheduler.common.enums.Priority;
-import org.apache.dolphinscheduler.common.enums.ReleaseState;
-import org.apache.dolphinscheduler.common.enums.UserType;
-import org.apache.dolphinscheduler.common.enums.WarningType;
+import org.apache.dolphinscheduler.common.enums.*;
import org.apache.dolphinscheduler.common.model.Server;
import org.apache.dolphinscheduler.common.utils.DateUtils;
-import org.apache.dolphinscheduler.common.utils.JSONUtils;
+import org.apache.dolphinscheduler.common.utils.*;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.ProcessDefinition;
import org.apache.dolphinscheduler.dao.entity.Project;
@@ -38,18 +34,12 @@ import org.apache.dolphinscheduler.dao.entity.User;
import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper;
import org.apache.dolphinscheduler.dao.mapper.ProjectMapper;
import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dolphinscheduler.service.process.ProcessService;
import org.apache.dolphinscheduler.service.quartz.ProcessScheduleJob;
import org.apache.dolphinscheduler.service.quartz.QuartzExecutors;
import org.apache.dolphinscheduler.service.quartz.cron.CronUtils;
-
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -57,8 +47,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
-import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import java.text.ParseException;
+import java.util.*;
/**
* scheduler service
@@ -96,10 +86,12 @@ public class SchedulerService extends BaseService {
* @param projectName project name
* @param processDefineId process definition id
* @param schedule scheduler
- * @param warningType warning type
+ * @param warningType warning type
* @param warningGroupId warning group id
* @param failureStrategy failure strategy
* @param processInstancePriority process instance priority
+ * @param receivers receivers
+ * @param receiversCc receivers cc
* @param workerGroup worker group
* @return create result code
*/
@@ -110,10 +102,12 @@ public class SchedulerService extends BaseService {
WarningType warningType,
int warningGroupId,
FailureStrategy failureStrategy,
+ String receivers,
+ String receiversCc,
Priority processInstancePriority,
String workerGroup) {
- Map result = new HashMap();
+ Map result = new HashMap(5);
Project project = projectMapper.queryByName(projectName);
@@ -138,9 +132,9 @@ public class SchedulerService extends BaseService {
scheduleObj.setProcessDefinitionName(processDefinition.getName());
ScheduleParam scheduleParam = JSONUtils.parseObject(schedule, ScheduleParam.class);
- if (DateUtils.differSec(scheduleParam.getStartTime(), scheduleParam.getEndTime()) == 0) {
+ if (DateUtils.differSec(scheduleParam.getStartTime(),scheduleParam.getEndTime()) == 0) {
logger.warn("The start time must not be the same as the end");
- putMsg(result, Status.SCHEDULE_START_TIME_END_TIME_SAME);
+ putMsg(result,Status.SCHEDULE_START_TIME_END_TIME_SAME);
return result;
}
scheduleObj.setStartTime(scheduleParam.getStartTime());
@@ -167,7 +161,8 @@ public class SchedulerService extends BaseService {
/**
* updateProcessInstance receivers and cc by process definition id
*/
- processDefinition.setWarningGroupId(warningGroupId);
+ processDefinition.setReceivers(receivers);
+ processDefinition.setReceiversCc(receiversCc);
processDefinitionMapper.updateById(processDefinition);
// return scheduler object with ID
@@ -178,6 +173,7 @@ public class SchedulerService extends BaseService {
return result;
}
+
/**
* updateProcessInstance schedule
*
@@ -190,6 +186,8 @@ public class SchedulerService extends BaseService {
* @param failureStrategy failure strategy
* @param workerGroup worker group
* @param processInstancePriority process instance priority
+ * @param receiversCc receiver cc
+ * @param receivers receivers
* @param scheduleStatus schedule status
* @return update result code
*/
@@ -201,6 +199,8 @@ public class SchedulerService extends BaseService {
WarningType warningType,
int warningGroupId,
FailureStrategy failureStrategy,
+ String receivers,
+ String receiversCc,
ReleaseState scheduleStatus,
Priority processInstancePriority,
String workerGroup) {
@@ -240,9 +240,9 @@ public class SchedulerService extends BaseService {
// updateProcessInstance param
if (StringUtils.isNotEmpty(scheduleExpression)) {
ScheduleParam scheduleParam = JSONUtils.parseObject(scheduleExpression, ScheduleParam.class);
- if (DateUtils.differSec(scheduleParam.getStartTime(), scheduleParam.getEndTime()) == 0) {
+ if (DateUtils.differSec(scheduleParam.getStartTime(),scheduleParam.getEndTime()) == 0) {
logger.warn("The start time must not be the same as the end");
- putMsg(result, Status.SCHEDULE_START_TIME_END_TIME_SAME);
+ putMsg(result,Status.SCHEDULE_START_TIME_END_TIME_SAME);
return result;
}
schedule.setStartTime(scheduleParam.getStartTime());
@@ -275,8 +275,8 @@ public class SchedulerService extends BaseService {
/**
* updateProcessInstance recipients and cc by process definition ID
*/
- processDefinition.setWarningGroupId(warningGroupId);
-
+ processDefinition.setReceivers(receivers);
+ processDefinition.setReceiversCc(receiversCc);
processDefinitionMapper.updateById(processDefinition);
putMsg(result, Status.SUCCESS);
@@ -290,7 +290,7 @@ public class SchedulerService extends BaseService {
* @param loginUser login user
* @param projectName project name
* @param id scheduler id
- * @param scheduleStatus schedule status
+ * @param scheduleStatus schedule status
* @return publish result code
*/
@Transactional(rollbackFor = RuntimeException.class)
@@ -316,7 +316,7 @@ public class SchedulerService extends BaseService {
return result;
}
// check schedule release state
- if (scheduleObj.getReleaseState() == scheduleStatus) {
+ if(scheduleObj.getReleaseState() == scheduleStatus){
logger.info("schedule release is already {},needn't to change schedule id: {} from {} to {}",
scheduleObj.getReleaseState(), scheduleObj.getId(), scheduleObj.getReleaseState(), scheduleStatus);
putMsg(result, Status.SCHEDULE_CRON_REALEASE_NEED_NOT_CHANGE, scheduleStatus);
@@ -328,9 +328,9 @@ public class SchedulerService extends BaseService {
return result;
}
- if (scheduleStatus == ReleaseState.ONLINE) {
+ if(scheduleStatus == ReleaseState.ONLINE){
// check process definition release state
- if (processDefinition.getReleaseState() != ReleaseState.ONLINE) {
+ if(processDefinition.getReleaseState() != ReleaseState.ONLINE){
logger.info("not release process definition id: {} , name : {}",
processDefinition.getId(), processDefinition.getName());
putMsg(result, Status.PROCESS_DEFINE_NOT_RELEASE, processDefinition.getName());
@@ -340,15 +340,15 @@ public class SchedulerService extends BaseService {
List subProcessDefineIds = new ArrayList<>();
processService.recurseFindSubProcessId(scheduleObj.getProcessDefinitionId(), subProcessDefineIds);
Integer[] idArray = subProcessDefineIds.toArray(new Integer[subProcessDefineIds.size()]);
- if (subProcessDefineIds.size() > 0) {
+ if (subProcessDefineIds.size() > 0){
List subProcessDefinitionList =
processDefinitionMapper.queryDefinitionListByIdList(idArray);
- if (subProcessDefinitionList != null && subProcessDefinitionList.size() > 0) {
- for (ProcessDefinition subProcessDefinition : subProcessDefinitionList) {
+ if (subProcessDefinitionList != null && subProcessDefinitionList.size() > 0){
+ for (ProcessDefinition subProcessDefinition : subProcessDefinitionList){
/**
* if there is no online process, exit directly
*/
- if (subProcessDefinition.getReleaseState() != ReleaseState.ONLINE) {
+ if (subProcessDefinition.getReleaseState() != ReleaseState.ONLINE){
logger.info("not release process definition id: {} , name : {}",
subProcessDefinition.getId(), subProcessDefinition.getName());
putMsg(result, Status.PROCESS_DEFINE_NOT_RELEASE, subProcessDefinition.getId());
@@ -362,6 +362,7 @@ public class SchedulerService extends BaseService {
// check master server exists
List masterServers = monitorService.getServerListFromZK(true);
+
if (masterServers.size() == 0) {
putMsg(result, Status.MASTER_NOT_EXISTS);
return result;
@@ -398,6 +399,8 @@ public class SchedulerService extends BaseService {
return result;
}
+
+
/**
* query schedule
*
@@ -405,7 +408,7 @@ public class SchedulerService extends BaseService {
* @param projectName project name
* @param processDefineId process definition id
* @param pageNo page number
- * @param pageSize page size
+ * @param pageSize page size
* @param searchVal search value
* @return schedule list page
*/
@@ -431,8 +434,9 @@ public class SchedulerService extends BaseService {
page, processDefineId, searchVal
);
+
PageInfo pageInfo = new PageInfo(pageNo, pageSize);
- pageInfo.setTotalCount((int) scheduleIPage.getTotal());
+ pageInfo.setTotalCount((int)scheduleIPage.getTotal());
pageInfo.setLists(scheduleIPage.getRecords());
result.put(Constants.DATA_LIST, pageInfo);
putMsg(result, Status.SUCCESS);
@@ -496,8 +500,8 @@ public class SchedulerService extends BaseService {
String jobName = QuartzExecutors.buildJobName(scheduleId);
String jobGroupName = QuartzExecutors.buildJobGroupName(projectId);
- if (!QuartzExecutors.getInstance().deleteJob(jobName, jobGroupName)) {
- logger.warn("set offline failure:projectId:{},scheduleId:{}", projectId, scheduleId);
+ if(!QuartzExecutors.getInstance().deleteJob(jobName, jobGroupName)){
+ logger.warn("set offline failure:projectId:{},scheduleId:{}",projectId,scheduleId);
throw new ServiceException("set offline failure");
}
@@ -547,18 +551,19 @@ public class SchedulerService extends BaseService {
}
// Determine if the login user is the owner of the schedule
- if (loginUser.getId() != schedule.getUserId()
- && loginUser.getUserType() != UserType.ADMIN_USER) {
+ if (loginUser.getId() != schedule.getUserId() &&
+ loginUser.getUserType() != UserType.ADMIN_USER) {
putMsg(result, Status.USER_NO_OPERATION_PERM);
return result;
}
// check schedule is already online
- if (schedule.getReleaseState() == ReleaseState.ONLINE) {
- putMsg(result, Status.SCHEDULE_CRON_STATE_ONLINE, schedule.getId());
+ if(schedule.getReleaseState() == ReleaseState.ONLINE){
+ putMsg(result, Status.SCHEDULE_CRON_STATE_ONLINE,schedule.getId());
return result;
}
+
int delete = scheduleMapper.deleteById(scheduleId);
if (delete > 0) {
@@ -577,7 +582,7 @@ public class SchedulerService extends BaseService {
* @param schedule schedule expression
* @return the next five fire time
*/
- public Map previewSchedule(User loginUser, String projectName, String schedule) {
+ public Map previewSchedule(User loginUser, String projectName, String schedule) {
Map result = new HashMap<>();
CronExpression cronExpression;
ScheduleParam scheduleParam = JSONUtils.parseObject(schedule, ScheduleParam.class);
@@ -588,11 +593,11 @@ public class SchedulerService extends BaseService {
try {
cronExpression = CronUtils.parse2CronExpression(scheduleParam.getCrontab());
} catch (ParseException e) {
- logger.error(e.getMessage(), e);
- putMsg(result, Status.PARSE_TO_CRON_EXPRESSION_ERROR);
+ logger.error(e.getMessage(),e);
+ putMsg(result,Status.PARSE_TO_CRON_EXPRESSION_ERROR);
return result;
}
- List selfFireDateList = CronUtils.getSelfFireDateList(startTime, endTime, cronExpression, Constants.PREVIEW_SCHEDULE_EXECUTE_COUNT);
+ List selfFireDateList = CronUtils.getSelfFireDateList(startTime, endTime,cronExpression,Constants.PREVIEW_SCHEDULE_EXECUTE_COUNT);
result.put(Constants.DATA_LIST, selfFireDateList.stream().map(t -> DateUtils.dateToString(t)));
putMsg(result, Status.SUCCESS);
return result;
diff --git a/dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/classloader/ThreadContextClassLoader.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UserAlertGroupService.java
similarity index 58%
rename from dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/classloader/ThreadContextClassLoader.java
rename to dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UserAlertGroupService.java
index b905ef72b7..502185709f 100644
--- a/dolphinscheduler-spi/src/main/java/org/apache/dolphinscheduler/spi/classloader/ThreadContextClassLoader.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UserAlertGroupService.java
@@ -14,22 +14,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package org.apache.dolphinscheduler.api.service;
-package org.apache.dolphinscheduler.spi.classloader;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import org.apache.dolphinscheduler.dao.entity.UserAlertGroup;
+import org.apache.dolphinscheduler.dao.mapper.UserAlertGroupMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
-import java.io.Closeable;
+/**
+ *
+ */
+@Service
+public class UserAlertGroupService extends ServiceImpl {
-public class ThreadContextClassLoader
- implements Closeable {
- private final ClassLoader threadContextClassLoader;
+ @Autowired
+ private UserAlertGroupMapper userAlertGroupMapper;
- public ThreadContextClassLoader(ClassLoader newThreadContextClassLoader) {
- this.threadContextClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(newThreadContextClassLoader);
+ boolean deleteByAlertGroupId(Integer groupId) {
+ return userAlertGroupMapper.deleteByAlertgroupId(groupId) >= 1;
}
- @Override
- public void close() {
- Thread.currentThread().setContextClassLoader(threadContextClassLoader);
- }
}
diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java
index 5fc5e1ee13..3fb5f64346 100644
--- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java
+++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java
@@ -131,7 +131,7 @@ public class UsersService extends BaseService {
String queue,
int state) throws Exception {
- Map result = new HashMap<>();
+ Map