Browse Source

merge from dev

pull/3/MERGE
lenboo 4 years ago
parent
commit
010b49c933
  1. 3
      ambari_plugin/common-services/DOLPHIN/1.3.0/configuration/dolphin-env.xml
  2. 3
      ambari_plugin/common-services/DOLPHIN/1.3.3/configuration/dolphin-env.xml
  3. 2
      docker/build/README.md
  4. 2
      docker/build/README_zh_CN.md
  5. 2
      docker/build/conf/dolphinscheduler/env/dolphinscheduler_env.sh.tpl
  6. 3
      docker/build/conf/dolphinscheduler/worker.properties.tpl
  7. 2
      docker/build/startup-init-conf.sh
  8. 2
      docker/docker-swarm/docker-compose.yml
  9. 2
      docker/docker-swarm/docker-stack.yml
  10. 4
      docker/kubernetes/dolphinscheduler/values.yaml
  11. 8
      dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java
  12. 262
      dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java
  13. 4
      dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/AlertPluginManagerTest.java
  14. 2
      dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java
  15. 9
      dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/PropertyUtilsTest.java
  16. 4
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java
  17. 8
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionService.java
  18. 5
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/AlertGroupServiceImpl.java
  19. 5
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/AlertPluginInstanceServiceImpl.java
  20. 12
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ProcessDefinitionServiceImpl.java
  21. 8
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/QueueServiceImpl.java
  22. 66
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java
  23. 7
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/TenantServiceImpl.java
  24. 3
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java
  25. 3
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/WorkFlowLineageServiceImpl.java
  26. 13
      dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/WorkerGroupServiceImpl.java
  27. 2
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java
  28. 2
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java
  29. 13
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java
  30. 17
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java
  31. 6
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java
  32. 1
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java
  33. 10
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java
  34. 13
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java
  35. 28
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/sql/SqlParameters.java
  36. 33
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/BooleanUtils.java
  37. 34
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java
  38. 14
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/PropertyUtils.java
  39. 50
      dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/ResInfo.java
  40. 4
      dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/task/DataxParametersTest.java
  41. 68
      dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/task/SqlParametersTest.java
  42. 16
      dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/OSUtilsTest.java
  43. 3
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/PluginDao.java
  44. 23
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/TaskRecordDao.java
  45. 33
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/datasource/SpringConnectionFactory.java
  46. 7
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapper.java
  47. 7
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapper.java
  48. 7
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ProcessDefinitionMapper.java
  49. 7
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/QueueMapper.java
  50. 52
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ResourceMapper.java
  51. 16
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ResourceUserMapper.java
  52. 7
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/TenantMapper.java
  53. 9
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/UserMapper.java
  54. 162
      dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/PropertyUtils.java
  55. 7
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapper.xml
  56. 6
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapper.xml
  57. 7
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ProcessDefinitionMapper.xml
  58. 12
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/QueueMapper.xml
  59. 131
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ResourceMapper.xml
  60. 14
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ResourceUserMapper.xml
  61. 5
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/TenantMapper.xml
  62. 7
      dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml
  63. 9
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapperTest.java
  64. 8
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapperTest.java
  65. 19
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/QueueMapperTest.java
  66. 68
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/ResourceMapperTest.java
  67. 10
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/TenantMapperTest.java
  68. 10
      dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/UserMapperTest.java
  69. 143
      dolphinscheduler-remote/src/main/java/org/apache/dolphinscheduler/remote/utils/Host.java
  70. 11
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/NettyRemotingClientTest.java
  71. 10
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/future/ResponseFutureTest.java
  72. 8
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/log/RemoveTaskLogRequestCommandTest.java
  73. 7
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/log/RemoveTaskLogResponseCommandTest.java
  74. 23
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/utils/HostTest.java
  75. 5
      dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/utils/NettyUtilTest.java
  76. 44
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/CommonHostManager.java
  77. 40
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/LowerWeightHostManager.java
  78. 9
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/RandomHostManager.java
  79. 7
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/RoundRobinHostManager.java
  80. 44
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWeight.java
  81. 77
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWorker.java
  82. 14
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RandomSelector.java
  83. 27
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RoundRobinSelector.java
  84. 4
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/registry/MasterRegistry.java
  85. 13
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterExecThread.java
  86. 28
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/registry/HeartBeatTask.java
  87. 16
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/config/WorkerConfig.java
  88. 4
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/processor/TaskExecuteProcessor.java
  89. 24
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/registry/WorkerRegistry.java
  90. 10
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/datax/DataxTask.java
  91. 1
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/shell/ShellTask.java
  92. 28
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/sql/SqlTask.java
  93. 2
      dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/zk/ZKMasterClient.java
  94. 3
      dolphinscheduler-server/src/main/resources/worker.properties
  95. 43
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWorkerTest.java
  96. 22
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/LowerWeightRoundRobinTest.java
  97. 10
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RandomSelectorTest.java
  98. 36
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RoundRobinSelectorTest.java
  99. 3
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/registry/MasterRegistryTest.java
  100. 6
      dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/registry/DependencyConfig.java
  101. Some files were not shown because too many files have changed in this diff Show More

3
ambari_plugin/common-services/DOLPHIN/1.3.0/configuration/dolphin-env.xml

@ -112,7 +112,8 @@ export SPARK_HOME2=/opt/soft/spark2
export PYTHON_HOME=/opt/soft/python
export JAVA_HOME=/opt/soft/java
export HIVE_HOME=/opt/soft/hive
export FLINK_HOME=/opt/soft/flink</value>
export FLINK_HOME=/opt/soft/flink
export DATAX_HOME=/opt/soft/datax</value>
<value-attributes>
<type>content</type>
<empty-value-valid>false</empty-value-valid>

3
ambari_plugin/common-services/DOLPHIN/1.3.3/configuration/dolphin-env.xml

@ -112,7 +112,8 @@ export SPARK_HOME2=/opt/soft/spark2
export PYTHON_HOME=/opt/soft/python
export JAVA_HOME=/opt/soft/java
export HIVE_HOME=/opt/soft/hive
export FLINK_HOME=/opt/soft/flink</value>
export FLINK_HOME=/opt/soft/flink
export DATAX_HOME=/opt/soft/datax</value>
<value-attributes>
<type>content</type>
<empty-value-valid>false</empty-value-valid>

2
docker/build/README.md

@ -209,7 +209,7 @@ This environment variable sets `FLINK_HOME`. The default value is `/opt/soft/fli
**`DATAX_HOME`**
This environment variable sets `DATAX_HOME`. The default value is `/opt/soft/datax/bin/datax.py`.
This environment variable sets `DATAX_HOME`. The default value is `/opt/soft/datax`.
**`DOLPHINSCHEDULER_DATA_BASEDIR_PATH`**

2
docker/build/README_zh_CN.md

@ -209,7 +209,7 @@ DolphinScheduler Docker 容器通过环境变量进行配置,缺省时将会
**`DATAX_HOME`**
配置`dolphinscheduler`的`DATAX_HOME`,默认值 `/opt/soft/datax/bin/datax。py`
配置`dolphinscheduler`的`DATAX_HOME`,默认值 `/opt/soft/datax`
**`DOLPHINSCHEDULER_DATA_BASEDIR_PATH`**

2
docker/build/conf/dolphinscheduler/env/dolphinscheduler_env.sh.tpl vendored

@ -25,4 +25,4 @@ export HIVE_HOME=$HIVE_HOME
export FLINK_HOME=$FLINK_HOME
export DATAX_HOME=$DATAX_HOME
export PATH=$HADOOP_HOME/bin:$SPARK_HOME1/bin:$SPARK_HOME2/bin:$PYTHON_HOME/bin:$JAVA_HOME/bin:$HIVE_HOME/bin:$PATH:$FLINK_HOME/bin:$DATAX_HOME:$PATH
export PATH=$HADOOP_HOME/bin:$SPARK_HOME1/bin:$SPARK_HOME2/bin:$PYTHON_HOME/bin:$JAVA_HOME/bin:$HIVE_HOME/bin:$FLINK_HOME/bin:$DATAX_HOME/bin:$PATH

3
docker/build/conf/dolphinscheduler/worker.properties.tpl

@ -21,6 +21,9 @@ worker.exec.threads=${WORKER_EXEC_THREADS}
# worker heartbeat interval
worker.heartbeat.interval=${WORKER_HEARTBEAT_INTERVAL}
# worker tenant auto create
worker.tenant.auto.create=true
# only less than cpu avg load, worker server can work. default value -1: the number of cpu cores * 2
worker.max.cpuload.avg=${WORKER_MAX_CPULOAD_AVG}

2
docker/build/startup-init-conf.sh

@ -46,7 +46,7 @@ export PYTHON_HOME=${PYTHON_HOME:-"/usr"}
export JAVA_HOME=${JAVA_HOME:-"/usr/lib/jvm/java-1.8-openjdk"}
export HIVE_HOME=${HIVE_HOME:-"/opt/soft/hive"}
export FLINK_HOME=${FLINK_HOME:-"/opt/soft/flink"}
export DATAX_HOME=${DATAX_HOME:-"/opt/soft/datax/bin/datax.py"}
export DATAX_HOME=${DATAX_HOME:-"/opt/soft/datax"}
# common env
export DOLPHINSCHEDULER_DATA_BASEDIR_PATH=${DOLPHINSCHEDULER_DATA_BASEDIR_PATH:-"/tmp/dolphinscheduler"}
export DOLPHINSCHEDULER_OPTS=${DOLPHINSCHEDULER_OPTS:-""}

2
docker/docker-swarm/docker-compose.yml

@ -181,7 +181,7 @@ services:
JAVA_HOME: "/usr/lib/jvm/java-1.8-openjdk"
HIVE_HOME: "/opt/soft/hive"
FLINK_HOME: "/opt/soft/flink"
DATAX_HOME: "/opt/soft/datax/bin/datax.py"
DATAX_HOME: "/opt/soft/datax"
DOLPHINSCHEDULER_DATA_BASEDIR_PATH: /tmp/dolphinscheduler
DOLPHINSCHEDULER_OPTS: "-Xms1g -Xmx1g -Xmn512m"
DATABASE_TYPE: postgresql

2
docker/docker-swarm/docker-stack.yml

@ -175,7 +175,7 @@ services:
JAVA_HOME: "/usr/lib/jvm/java-1.8-openjdk"
HIVE_HOME: "/opt/soft/hive"
FLINK_HOME: "/opt/soft/flink"
DATAX_HOME: "/opt/soft/datax/bin/datax.py"
DATAX_HOME: "/opt/soft/datax"
DOLPHINSCHEDULER_DATA_BASEDIR_PATH: /tmp/dolphinscheduler
DOLPHINSCHEDULER_OPTS: "-Xms1g -Xmx1g -Xmn512m"
DATABASE_TYPE: postgresql

4
docker/kubernetes/dolphinscheduler/values.yaml

@ -80,8 +80,8 @@ common:
- "export JAVA_HOME=/usr/lib/jvm/java-1.8-openjdk"
- "export HIVE_HOME=/opt/soft/hive"
- "export FLINK_HOME=/opt/soft/flink"
- "export DATAX_HOME=/opt/soft/datax/bin/datax.py"
- "export PATH=$HADOOP_HOME/bin:$SPARK_HOME1/bin:$SPARK_HOME2/bin:$JAVA_HOME/bin:$HIVE_HOME/bin:$FLINK_HOME/bin:$PATH"
- "export DATAX_HOME=/opt/soft/datax"
- "export PATH=$HADOOP_HOME/bin:$SPARK_HOME1/bin:$SPARK_HOME2/bin:$PYTHON_HOME/bin:$JAVA_HOME/bin:$HIVE_HOME/bin:$FLINK_HOME/bin:$DATAX_HOME/bin:$PATH"
DOLPHINSCHEDULER_DATA_BASEDIR_PATH: "/tmp/dolphinscheduler"
RESOURCE_STORAGE_TYPE: "HDFS"
RESOURCE_UPLOAD_PATH: "/dolphinscheduler"

8
dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java

@ -17,16 +17,17 @@
package org.apache.dolphinscheduler.alert;
import static org.apache.dolphinscheduler.alert.utils.Constants.ALERT_PROPERTIES_PATH;
import static org.apache.dolphinscheduler.common.Constants.ALERT_RPC_PORT;
import org.apache.dolphinscheduler.alert.plugin.AlertPluginManager;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginLoader;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginManagerConfig;
import org.apache.dolphinscheduler.alert.processor.AlertRequestProcessor;
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.plugin.DolphinPluginLoader;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginManagerConfig;
import org.apache.dolphinscheduler.common.thread.Stopper;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
import org.apache.dolphinscheduler.dao.AlertDao;
import org.apache.dolphinscheduler.dao.DaoFactory;
import org.apache.dolphinscheduler.dao.entity.Alert;
@ -140,6 +141,7 @@ public class AlertServer {
* start
*/
public void start() {
PropertyUtils.loadPropertyFile(ALERT_PROPERTIES_PATH);
initPlugin();
initRemoteServer();
logger.info("alert server ready start ");

262
dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/PropertyUtils.java

@ -1,262 +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.utils;
import static org.apache.dolphinscheduler.alert.utils.Constants.ALERT_PROPERTIES_PATH;
import org.apache.dolphinscheduler.common.utils.IOUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.regex.PatternSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* property utils
* single instance
*/
public class PropertyUtils {
/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);
private static final Properties properties = new Properties();
/**
* init properties
*/
private static final PropertyUtils propertyUtils = new PropertyUtils();
private PropertyUtils() {
init();
}
private void init() {
String[] propertyFiles = new String[]{ALERT_PROPERTIES_PATH};
for (String fileName : propertyFiles) {
InputStream fis = null;
try {
fis = PropertyUtils.class.getResourceAsStream(fileName);
properties.load(fis);
} catch (IOException e) {
logger.error(e.getMessage(), e);
if (fis != null) {
IOUtils.closeQuietly(fis);
}
System.exit(1);
} finally {
IOUtils.closeQuietly(fis);
}
}
}
/**
* get property value
*
* @param key property name
* @return the value
*/
public static String getString(String key) {
if (StringUtils.isEmpty(key)) {
return null;
}
return properties.getProperty(key.trim());
}
/**
* get property value
*
* @param key property name
* @param defaultVal default value
* @return property value
*/
public static String getString(String key, String defaultVal) {
String val = properties.getProperty(key.trim());
return val == null ? defaultVal : val;
}
/**
* get property value
*
* @param key property name
* @return get property int value , if key == null, then return -1
*/
public static int getInt(String key) {
return getInt(key, -1);
}
/**
* get int value
*
* @param key the key
* @param defaultValue the default value
* @return the value related the key or the default value if the key not existed
*/
public static int getInt(String key, int defaultValue) {
String value = getString(key);
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.info(e.getMessage(), e);
}
return defaultValue;
}
/**
* get property value
*
* @param key property name
* @return the boolean result value
*/
public static Boolean getBoolean(String key) {
if (StringUtils.isEmpty(key)) {
return false;
}
String value = properties.getProperty(key.trim());
if (null != value) {
return Boolean.parseBoolean(value);
}
return false;
}
/**
* get long value
*
* @param key the key
* @return if the value not existed, return -1, or will return the related value
*/
public static long getLong(String key) {
return getLong(key, -1);
}
/**
* get long value
*
* @param key the key
* @param defaultVal the default value
* @return the value related the key or the default value if the key not existed
*/
public static long getLong(String key, long defaultVal) {
String val = getString(key);
if (val == null) {
return defaultVal;
}
try {
return Long.parseLong(val);
} catch (NumberFormatException e) {
logger.info(e.getMessage(), e);
}
return defaultVal;
}
/**
* get double value
*
* @param key the key
* @return if the value not existed, return -1.0, or will return the related value
*/
public static double getDouble(String key) {
return getDouble(key, -1.0);
}
/**
* get double value
*
* @param key the key
* @param defaultVal the default value
* @return the value related the key or the default value if the key not existed
*/
public static double getDouble(String key, double defaultVal) {
String val = getString(key);
if (val == null) {
return defaultVal;
}
try {
return Double.parseDouble(val);
} catch (NumberFormatException e) {
logger.info(e.getMessage(), e);
}
return defaultVal;
}
/**
* get array
*
* @param key property name
* @param splitStr separator
* @return the result array
*/
public static String[] getArray(String key, String splitStr) {
String value = getString(key);
if (value == null || StringUtils.isEmpty(splitStr)) {
return null;
}
try {
return value.split(splitStr);
} catch (PatternSyntaxException e) {
logger.info(e.getMessage(), e);
}
return null;
}
/**
* get enum
*
* @param key the key
* @param type the class type
* @param defaultValue the default value
* @param <T> the generic class type
* @return get enum value
*/
public static <T extends Enum<T>> T getEnum(String key, Class<T> type,
T defaultValue) {
String val = getString(key);
if (val == null) {
return defaultValue;
}
try {
return Enum.valueOf(type, val);
} catch (IllegalArgumentException e) {
logger.info(e.getMessage(), e);
}
return defaultValue;
}
}

4
dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/AlertPluginManagerTest.java

@ -19,7 +19,7 @@ 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.common.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginLoader;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginManagerConfig;
import org.apache.dolphinscheduler.spi.utils.StringUtils;
@ -48,7 +48,7 @@ public class AlertPluginManagerTest {
String path = Objects.requireNonNull(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());
alertPluginManagerConfig.setInstalledPluginsDir(PropertyUtils.getString(AlertServer.ALERT_PLUGIN_DIR, Constants.ALERT_PLUGIN_PATH).trim());
}
if (StringUtils.isNotBlank(PropertyUtils.getString(AlertServer.MAVEN_LOCAL_REPOSITORY))) {

2
dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/plugin/EmailAlertPluginTest.java

@ -20,7 +20,7 @@ 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.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.enums.AlertStatus;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginLoader;
import org.apache.dolphinscheduler.common.plugin.DolphinPluginManagerConfig;

9
dolphinscheduler-alert/src/test/java/org/apache/dolphinscheduler/alert/utils/PropertyUtilsTest.java

@ -23,6 +23,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.enums.ZKNodeType;
import org.junit.Test;
@ -119,15 +120,15 @@ public class PropertyUtilsTest {
public void testGetDouble() {
//Expected 3.0
double result = PropertyUtils.getDouble("test.server.factor");
double result = PropertyUtils.getDouble("test.server.factor", 3.0);
assertEquals(3.0, result, 0);
//If key is null, then return -1.0
result = PropertyUtils.getDouble(null);
result = PropertyUtils.getDouble(null, -1.0);
assertEquals(-1.0, result, 0);
//If key is undefine in alert.properties, then return -1
result = PropertyUtils.getDouble("abc");
result = PropertyUtils.getDouble("abc", -1.0);
assertEquals(-1.0, result, 0);
//If key is undefine in alert.properties, and there is a defaultval, then return defaultval
@ -135,7 +136,7 @@ public class PropertyUtilsTest {
assertEquals(5.0, result, 0);
//If the value can not parse to double ,it will log the error and return -1.0
result = PropertyUtils.getDouble("test.server.testnumber");
result = PropertyUtils.getDouble("test.server.testnumber", -1.0);
assertEquals(-1.0, result, 0);
}

4
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java

@ -301,7 +301,9 @@ public enum Status {
PLUGIN_INSTANCE_ALREADY_EXIT(110010, "plugin instance already exit", "该告警插件实例已存在"),
LIST_PAGING_ALERT_PLUGIN_INSTANCE_ERROR(110011, "query plugin instance page error", "分页查询告警实例失败"),
DELETE_ALERT_PLUGIN_INSTANCE_ERROR_HAS_ALERT_GROUP_ASSOCIATED(110012, "failed to delete the alert instance, there is an alarm group associated with this alert instance",
"删除告警实例失败,存在与此告警实例关联的警报组");
"删除告警实例失败,存在与此告警实例关联的警报组"),
PROCESS_DEFINITION_VERSION_IS_USED(110013,"this process definition version is used","此工作流定义版本被使用");
private final int code;
private final String enMsg;

8
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionService.java

@ -299,5 +299,13 @@ public interface ProcessDefinitionService {
*/
Map<String, Object> deleteByProcessDefinitionIdAndVersion(User loginUser, String projectName,
int processDefinitionId, long version);
/**
* check has associated process definition
*
* @param processDefinitionId process definition id
* @param version version
* @return The query result has a specific process definition return true
*/
boolean checkHasAssociatedProcessDefinition(int processDefinitionId, long version);
}

5
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/AlertGroupServiceImpl.java

@ -21,7 +21,7 @@ import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.service.AlertGroupService;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.AlertGroup;
import org.apache.dolphinscheduler.dao.entity.User;
@ -207,7 +207,6 @@ public class AlertGroupServiceImpl extends BaseServiceImpl implements AlertGroup
*/
@Override
public boolean existGroupName(String groupName) {
List<AlertGroup> alertGroup = alertGroupMapper.queryByGroupName(groupName);
return CollectionUtils.isNotEmpty(alertGroup);
return BooleanUtils.isTrue(alertGroupMapper.existGroupName(groupName));
}
}

5
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/AlertPluginInstanceServiceImpl.java

@ -22,6 +22,7 @@ import org.apache.dolphinscheduler.api.service.AlertPluginInstanceService;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.vo.AlertPluginInstanceVO;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.dao.entity.AlertPluginInstance;
@ -82,7 +83,7 @@ public class AlertPluginInstanceServiceImpl extends BaseServiceImpl implements A
Map<String, Object> result = new HashMap<>();
if (CollectionUtils.isNotEmpty(alertPluginInstanceMapper.queryByInstanceName(alertPluginInstance.getInstanceName()))) {
if (BooleanUtils.isTrue(alertPluginInstanceMapper.existInstanceName(alertPluginInstance.getInstanceName()))) {
putMsg(result, Status.PLUGIN_INSTANCE_ALREADY_EXIT);
return result;
}
@ -183,7 +184,7 @@ public class AlertPluginInstanceServiceImpl extends BaseServiceImpl implements A
@Override
public boolean checkExistPluginInstanceName(String pluginInstanceName) {
return CollectionUtils.isNotEmpty(alertPluginInstanceMapper.queryByInstanceName(pluginInstanceName));
return BooleanUtils.isTrue(alertPluginInstanceMapper.existInstanceName(pluginInstanceName));
}
@Override

12
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ProcessDefinitionServiceImpl.java

@ -1676,6 +1676,18 @@ public class ProcessDefinitionServiceImpl extends BaseServiceImpl implements Pro
putMsg(result, Status.SUCCESS);
}
}
/**
* check has associated process definition
*
* @param processDefinitionId process definition id
* @param version version
* @return The query result has a specific process definition return true
*/
@Override
public boolean checkHasAssociatedProcessDefinition(int processDefinitionId, long version) {
Integer hasAssociatedDefinitionId = processDefinitionMapper.queryHasAssociatedDefinitionByIdAndVersion(processDefinitionId, version);
return Objects.nonNull(hasAssociatedDefinitionId);
}
/**
* query the pagination versions info by one certain process definition id

8
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/QueueServiceImpl.java

@ -22,7 +22,7 @@ import org.apache.dolphinscheduler.api.service.QueueService;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.Queue;
import org.apache.dolphinscheduler.dao.entity.User;
@ -270,7 +270,7 @@ public class QueueServiceImpl extends BaseServiceImpl implements QueueService {
* @return true if the queue not exists, otherwise return false
*/
private boolean checkQueueExist(String queue) {
return CollectionUtils.isNotEmpty(queueMapper.queryAllQueueList(queue, null));
return BooleanUtils.isTrue(queueMapper.existQueue(queue, null));
}
/**
@ -281,7 +281,7 @@ public class QueueServiceImpl extends BaseServiceImpl implements QueueService {
* @return true if the queue name not exists, otherwise return false
*/
private boolean checkQueueNameExist(String queueName) {
return CollectionUtils.isNotEmpty(queueMapper.queryAllQueueList(null, queueName));
return BooleanUtils.isTrue(queueMapper.existQueue(null, queueName));
}
/**
@ -293,7 +293,7 @@ public class QueueServiceImpl extends BaseServiceImpl implements QueueService {
* @return true if need to update user
*/
private boolean checkIfQueueIsInUsing (String oldQueue, String newQueue) {
return !oldQueue.equals(newQueue) && CollectionUtils.isNotEmpty(userMapper.queryUserListByQueue(oldQueue));
return !oldQueue.equals(newQueue) && BooleanUtils.isTrue(userMapper.existUser(oldQueue));
}
}

66
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/ResourcesServiceImpl.java

@ -34,6 +34,7 @@ import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.ProgramType;
import org.apache.dolphinscheduler.common.enums.ResourceType;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.FileUtils;
import org.apache.dolphinscheduler.common.utils.HadoopUtils;
@ -251,8 +252,8 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
* @return true if resource exists
*/
private boolean checkResourceExists(String fullName, int userId, int type) {
List<Resource> resources = resourcesMapper.queryResourceList(fullName, userId, type);
return resources != null && !resources.isEmpty();
Boolean existResource = resourcesMapper.existResource(fullName, userId, type);
return BooleanUtils.isTrue(existResource);
}
/**
@ -361,6 +362,7 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
Date now = new Date();
resource.setAlias(name);
resource.setFileName(name);
resource.setFullName(fullName);
resource.setDescription(desc);
resource.setUpdateTime(now);
@ -527,8 +529,10 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
}
}
IPage<Resource> resourceIPage = resourcesMapper.queryResourcePaging(page,
userId,directoryId, type.ordinal(), searchVal);
List<Integer> resourcesIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(userId, 0);
IPage<Resource> resourceIPage = resourcesMapper.queryResourcePaging(page, userId, directoryId, type.ordinal(), searchVal,resourcesIds);
PageInfo<Resource> pageInfo = new PageInfo<>(pageNo, pageSize);
pageInfo.setTotalCount((int)resourceIPage.getTotal());
pageInfo.setLists(resourceIPage.getRecords());
@ -613,12 +617,7 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
@Override
public Map<String, Object> queryResourceList(User loginUser, ResourceType type) {
Map<String, Object> result = new HashMap<>();
int userId = loginUser.getId();
if (isAdmin(loginUser)) {
userId = 0;
}
List<Resource> allResourceList = resourcesMapper.queryResourceListAuthored(userId, type.ordinal(),0);
List<Resource> allResourceList = queryAuthoredResourceList(loginUser, type);
Visitor resourceTreeVisitor = new ResourceTreeVisitor(allResourceList);
result.put(Constants.DATA_LIST, resourceTreeVisitor.visit().getChildren());
putMsg(result, Status.SUCCESS);
@ -636,11 +635,10 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
@Override
public Map<String, Object> queryResourceByProgramType(User loginUser, ResourceType type, ProgramType programType) {
Map<String, Object> result = new HashMap<>();
List<Resource> allResourceList = queryAuthoredResourceList(loginUser, type);
String suffix = ".jar";
int userId = loginUser.getId();
if (isAdmin(loginUser)) {
userId = 0;
}
if (programType != null) {
switch (programType) {
case JAVA:
@ -652,7 +650,6 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
default:
}
}
List<Resource> allResourceList = resourcesMapper.queryResourceListAuthored(userId, type.ordinal(),0);
List<Resource> resources = new ResourceFilter(suffix, new ArrayList<>(allResourceList)).filter();
Visitor resourceTreeVisitor = new ResourceTreeVisitor(resources);
result.put(Constants.DATA_LIST, resourceTreeVisitor.visit().getChildren());
@ -1171,8 +1168,7 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
List<Resource> list;
if (resourceList != null && !resourceList.isEmpty()) {
Set<Resource> resourceSet = new HashSet<>(resourceList);
List<Resource> authedResourceList = resourcesMapper.queryAuthorizedResourceList(userId);
List<Resource> authedResourceList = queryResourceList(userId, Constants.AUTHORIZE_WRITABLE_PERM);
getAuthorizedResourceList(resourceSet, authedResourceList);
list = new ArrayList<>(resourceSet);
} else {
@ -1247,7 +1243,7 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
if (isNotAdmin(loginUser, result)) {
return result;
}
List<Resource> authedResources = resourcesMapper.queryAuthorizedResourceList(userId);
List<Resource> authedResources = queryResourceList(userId, Constants.AUTHORIZE_WRITABLE_PERM);
Visitor visitor = new ResourceTreeVisitor(authedResources);
String visit = JSONUtils.toJsonString(visitor.visit(), SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
logger.info(visit);
@ -1327,4 +1323,38 @@ public class ResourcesServiceImpl extends BaseServiceImpl implements ResourcesSe
}
}
/**
* query authored resource list (own and authorized)
* @param loginUser login user
* @param type ResourceType
* @return all authored resource list
*/
private List<Resource> queryAuthoredResourceList(User loginUser, ResourceType type) {
List<Resource> relationResources;
int userId = loginUser.getId();
if (isAdmin(loginUser)) {
userId = 0;
relationResources = new ArrayList<>();
} else {
// query resource relation
relationResources = queryResourceList(userId, 0);
}
List<Resource> ownResourceList = resourcesMapper.queryResourceListAuthored(userId, type.ordinal());
ownResourceList.addAll(relationResources);
return ownResourceList;
}
/**
* query resource list by userId and perm
* @param userId userId
* @param perm perm
* @return resource list
*/
private List<Resource> queryResourceList(Integer userId, int perm) {
List<Integer> resIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(userId, perm);
return CollectionUtils.isEmpty(resIds) ? new ArrayList<>() : resourcesMapper.queryResourceListById(resIds);
}
}

7
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/TenantServiceImpl.java

@ -23,6 +23,7 @@ import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.RegexUtils;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.HadoopUtils;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
@ -95,7 +96,7 @@ public class TenantServiceImpl extends BaseServiceImpl implements TenantService
}
if (checkTenantExists(tenantCode)) {
putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, tenantCode);
putMsg(result, Status.OS_TENANT_CODE_EXIST, tenantCode);
return result;
}
@ -344,7 +345,7 @@ public class TenantServiceImpl extends BaseServiceImpl implements TenantService
* @return ture if the tenant code exists, otherwise return false
*/
private boolean checkTenantExists(String tenantCode) {
List<Tenant> tenants = tenantMapper.queryByTenantCode(tenantCode);
return CollectionUtils.isNotEmpty(tenants);
Boolean existTenant = tenantMapper.existTenant(tenantCode);
return BooleanUtils.isTrue(existTenant);
}
}

3
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java

@ -586,7 +586,8 @@ public class UsersServiceImpl extends BaseServiceImpl implements UsersService {
}
//get the authorized resource id list by user id
List<Resource> oldAuthorizedRes = resourceMapper.queryAuthorizedResourceList(userId);
List<Integer> resIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(userId, Constants.AUTHORIZE_WRITABLE_PERM);
List<Resource> oldAuthorizedRes = CollectionUtils.isEmpty(resIds) ? new ArrayList<>() : resourceMapper.queryResourceListById(resIds);
//if resource type is UDF,need check whether it is bound by UDF function
Set<Integer> oldAuthorizedResIds = oldAuthorizedRes.stream().map(Resource::getId).collect(Collectors.toSet());

3
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/WorkFlowLineageServiceImpl.java

@ -28,7 +28,6 @@ import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper;
import org.apache.dolphinscheduler.dao.mapper.ProjectMapper;
import org.apache.dolphinscheduler.dao.mapper.WorkFlowLineageMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@ -93,6 +92,7 @@ public class WorkFlowLineageServiceImpl extends BaseServiceImpl implements WorkF
workFlowLineage.setSourceWorkFlowId(String.valueOf(pre.getWorkFlowId()));
} else {
workFlowLineage.setSourceWorkFlowId(sourceWorkFlowId + "," + pre.getWorkFlowId());
}
} else {
@ -110,7 +110,6 @@ public class WorkFlowLineageServiceImpl extends BaseServiceImpl implements WorkF
getRelation(workFlowLineageMap, workFlowRelations, relation);
}
}
}
@Override

13
dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/WorkerGroupServiceImpl.java

@ -163,18 +163,13 @@ public class WorkerGroupServiceImpl extends BaseServiceImpl implements WorkerGro
if (CollectionUtils.isEmpty(childrenNodes)) {
continue;
}
String timeStamp = childrenNodes.get(0);
for (int i = 0; i < childrenNodes.size(); i++) {
childrenNodes.set(i, Host.of(childrenNodes.get(i)).getAddressAndWeight());
}
WorkerGroup wg = new WorkerGroup();
wg.setName(workerGroup);
if (isPaging) {
wg.setIpList(childrenNodes);
String registeredIpValue = zookeeperCachedOperator.get(workerGroupPath + SLASH + timeStamp);
wg.setCreateTime(DateUtils.stringToDate(registeredIpValue.split(",")[6]));
wg.setUpdateTime(DateUtils.stringToDate(registeredIpValue.split(",")[7]));
wg.setIpList(childrenNodes.stream().map(node -> Host.of(node).getIp()).collect(Collectors.toList()));
String registeredValue = zookeeperCachedOperator.get(workerGroupPath + SLASH + childrenNodes.get(0));
wg.setCreateTime(DateUtils.stringToDate(registeredValue.split(",")[6]));
wg.setUpdateTime(DateUtils.stringToDate(registeredValue.split(",")[7]));
}
workerGroups.add(wg);
}

2
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java

@ -156,7 +156,7 @@ public class AlertGroupServiceTest {
//group name not exist
boolean result = alertGroupService.existGroupName(groupName);
Assert.assertFalse(result);
Mockito.when(alertGroupMapper.queryByGroupName(groupName)).thenReturn(getList());
Mockito.when(alertGroupMapper.existGroupName(groupName)).thenReturn(true);
//group name exist
result = alertGroupService.existGroupName(groupName);

2
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java

@ -157,7 +157,7 @@ public class AlertPluginInstanceServiceTest {
@Test
public void testCreate() {
Mockito.when(alertPluginInstanceMapper.queryByInstanceName("test")).thenReturn(alertPluginInstances);
Mockito.when(alertPluginInstanceMapper.existInstanceName("test")).thenReturn(true);
Map<String, Object> result = alertPluginInstanceService.create(user, 1, "test", uiParams);
Assert.assertEquals(Status.PLUGIN_INSTANCE_ALREADY_EXIT, result.get(Constants.STATUS));
Mockito.when(alertPluginInstanceMapper.insert(Mockito.any())).thenReturn(1);

13
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java

@ -114,13 +114,13 @@ public class QueueServiceTest {
Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS));
}
@Test
public void testUpdateQueue() {
Mockito.when(queueMapper.selectById(1)).thenReturn(getQueue());
Mockito.when(queueMapper.queryAllQueueList("test", null)).thenReturn(getQueueList());
Mockito.when(queueMapper.queryAllQueueList(null, "test")).thenReturn(getQueueList());
Mockito.when(userMapper.queryUserListByQueue(queueName)).thenReturn(getUserList());
Mockito.when(queueMapper.existQueue("test", null)).thenReturn(true);
Mockito.when(queueMapper.existQueue(null, "test")).thenReturn(true);
// not exist
Map<String, Object> result = queueService.updateQueue(getLoginUser(),0,"queue",queueName);
@ -144,11 +144,12 @@ public class QueueServiceTest {
Assert.assertEquals(Status.SUCCESS.getCode(),((Status)result.get(Constants.STATUS)).getCode());
}
@Test
public void testVerifyQueue() {
Mockito.when(queueMapper.queryAllQueueList(queueName, null)).thenReturn(getQueueList());
Mockito.when(queueMapper.queryAllQueueList(null, queueName)).thenReturn(getQueueList());
Mockito.when(queueMapper.existQueue(queueName, null)).thenReturn(true);
Mockito.when(queueMapper.existQueue(null, queueName)).thenReturn(true);
//queue null
Result result = queueService.verifyQueue(null,queueName);
@ -175,8 +176,8 @@ public class QueueServiceTest {
logger.info(result.toString());
Assert.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode());
}
/**
* create admin user
* @return

17
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java

@ -169,7 +169,7 @@ public class ResourcesServiceTest {
Assert.assertEquals(Status.PARENT_RESOURCE_NOT_EXIST.getMsg(), result.getMsg());
//RESOURCE_EXIST
PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true);
Mockito.when(resourcesMapper.queryResourceList("/directoryTest", 0, 0)).thenReturn(getResourceList());
Mockito.when(resourcesMapper.existResource("/directoryTest", 0, 0)).thenReturn(true);
result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, -1, "/");
logger.info(result.toString());
Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg());
@ -227,7 +227,7 @@ public class ResourcesServiceTest {
Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg());
//RESOURCE_EXIST
Mockito.when(resourcesMapper.queryResourceList("/ResourcesServiceTest1.jar", 0, 0)).thenReturn(getResourceList());
Mockito.when(resourcesMapper.existResource("/ResourcesServiceTest1.jar", 0, 0)).thenReturn(true);
result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.FILE, null);
logger.info(result.toString());
Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg());
@ -266,8 +266,9 @@ public class ResourcesServiceTest {
IPage<Resource> resourcePage = new Page<>(1, 10);
resourcePage.setTotal(1);
resourcePage.setRecords(getResourceList());
Mockito.when(resourcesMapper.queryResourcePaging(Mockito.any(Page.class),
Mockito.eq(0), Mockito.eq(-1), Mockito.eq(0), Mockito.eq("test"))).thenReturn(resourcePage);
Mockito.eq(0), Mockito.eq(-1), Mockito.eq(0), Mockito.eq("test"), Mockito.any())).thenReturn(resourcePage);
Map<String, Object> result = resourcesService.queryResourceListPaging(loginUser, -1, ResourceType.FILE, "test", 1, 10);
logger.info(result.toString());
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
@ -281,7 +282,7 @@ public class ResourcesServiceTest {
User loginUser = new User();
loginUser.setId(0);
loginUser.setUserType(UserType.ADMIN_USER);
Mockito.when(resourcesMapper.queryResourceListAuthored(0, 0, 0)).thenReturn(getResourceList());
Mockito.when(resourcesMapper.queryResourceListAuthored(0, 0)).thenReturn(getResourceList());
Map<String, Object> result = resourcesService.queryResourceList(loginUser, ResourceType.FILE);
logger.info(result.toString());
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
@ -344,7 +345,7 @@ public class ResourcesServiceTest {
User user = new User();
user.setId(1);
Mockito.when(resourcesMapper.queryResourceList("/ResourcesServiceTest.jar", 0, 0)).thenReturn(getResourceList());
Mockito.when(resourcesMapper.existResource("/ResourcesServiceTest.jar", 0, 0)).thenReturn(true);
Result result = resourcesService.verifyResourceName("/ResourcesServiceTest.jar", ResourceType.FILE, user);
logger.info(result.toString());
Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg());
@ -615,7 +616,11 @@ public class ResourcesServiceTest {
Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS));
//SUCCESS
user.setUserType(UserType.ADMIN_USER);
Mockito.when(resourcesMapper.queryAuthorizedResourceList(1)).thenReturn(getResourceList());
List<Integer> resIds = new ArrayList<>();
resIds.add(1);
Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())).thenReturn(resIds);
Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getResourceList());
result = resourcesService.authorizedFile(user, 1);
logger.info(result.toString());
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));

6
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java

@ -79,7 +79,7 @@ public class TenantServiceTest {
public void testCreateTenant() {
User loginUser = getLoginUser();
Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getList());
Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true);
try {
//check tenantCode
Map<String, Object> result =
@ -90,7 +90,7 @@ public class TenantServiceTest {
//check exist
result = tenantService.createTenant(loginUser, tenantCode, 1, "TenantServiceTest");
logger.info(result.toString());
Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS));
Assert.assertEquals(Status.OS_TENANT_CODE_EXIST, result.get(Constants.STATUS));
// success
result = tenantService.createTenant(loginUser, "test", 1, "TenantServiceTest");
@ -186,7 +186,7 @@ public class TenantServiceTest {
@Test
public void testVerifyTenantCode() {
Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getList());
Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true);
// tenantCode not exist
Result result = tenantService.verifyTenantCode("s00000000000l887888885554444sfjdskfjslakslkdf");
logger.info(result.toString());

1
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java

@ -325,7 +325,6 @@ public class UsersServiceTest {
logger.info(result.toString());
Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS));
//success
when(resourceMapper.queryAuthorizedResourceList(1)).thenReturn(new ArrayList<Resource>());
when(resourceMapper.selectById(Mockito.anyInt())).thenReturn(getResource());
when(resourceUserMapper.deleteResourceUser(1, 0)).thenReturn(1);
result = usersService.grantResources(loginUser, 1, resourceIds);

10
dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java

@ -70,13 +70,13 @@ public class WorkerGroupServiceTest {
workerGroupStrList.add("test");
Mockito.when(zookeeperCachedOperator.getChildrenKeys(workerPath)).thenReturn(workerGroupStrList);
List<String> defaultIpList = new ArrayList<>();
defaultIpList.add("192.168.220.188:1234:100:1234567");
defaultIpList.add("192.168.220.189:1234:100:1234567");
List<String> defaultAddressList = new ArrayList<>();
defaultAddressList.add("192.168.220.188:1234");
defaultAddressList.add("192.168.220.189:1234");
Mockito.when(zookeeperCachedOperator.getChildrenKeys(workerPath + "/default")).thenReturn(defaultIpList);
Mockito.when(zookeeperCachedOperator.getChildrenKeys(workerPath + "/default")).thenReturn(defaultAddressList);
Mockito.when(zookeeperCachedOperator.get(workerPath + "/default" + "/" + defaultIpList.get(0))).thenReturn("0.01,0.17,0.03,25.83,8.0,1.0,2020-07-21 11:17:59,2020-07-21 14:39:20,0,13238");
Mockito.when(zookeeperCachedOperator.get(workerPath + "/default" + "/" + defaultAddressList.get(0))).thenReturn("0.01,0.17,0.03,25.83,8.0,1.0,2020-07-21 11:17:59,2020-07-21 14:39:20,0,13238");
}
/**

13
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java

@ -331,6 +331,11 @@ public final class Constants {
*/
public static final Pattern REGEX_MAIL_NAME = Pattern.compile("^([a-z0-9A-Z]+[_|\\-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
/**
* default display rows
*/
public static final int DEFAULT_DISPLAY_ROWS = 10;
/**
* read permission
*/
@ -385,6 +390,10 @@ public final class Constants {
*/
public static final double DEFAULT_WORKER_RESERVED_MEMORY = OSUtils.totalMemorySize() / 10;
/**
* worker host weight
*/
public static final int DEFAULT_WORKER_HOST_WEIGHT = 100;
/**
* default log cache rows num,output when reach the number
@ -470,6 +479,8 @@ public final class Constants {
public static final String CMD_PARAM_START_PARAMS = "StartParams";
public static final String CMD_PARAM_FATHER_PARAMS = "fatherParams";
/**
* complement data start date
*/
@ -547,7 +558,7 @@ public final class Constants {
* heartbeat for zk info length
*/
public static final int HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH = 10;
public static final int HEARTBEAT_WITH_WEIGHT_FOR_ZOOKEEPER_INFO_LENGTH = 11;
/**
* jar

28
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/sql/SqlParameters.java

@ -50,6 +50,16 @@ public class SqlParameters extends AbstractParameters {
*/
private int sqlType;
/**
* send email
*/
private Boolean sendEmail;
/**
* display rows
*/
private int displayRows;
/**
* udf list
*/
@ -124,6 +134,22 @@ public class SqlParameters extends AbstractParameters {
this.sqlType = sqlType;
}
public Boolean getSendEmail() {
return sendEmail;
}
public void setSendEmail(Boolean sendEmail) {
this.sendEmail = sendEmail;
}
public int getDisplayRows() {
return displayRows;
}
public void setDisplayRows(int displayRows) {
this.displayRows = displayRows;
}
public String getShowType() {
return showType;
}
@ -189,6 +215,8 @@ public class SqlParameters extends AbstractParameters {
+ ", datasource=" + datasource
+ ", sql='" + sql + '\''
+ ", sqlType=" + sqlType
+ ", sendEmail=" + sendEmail
+ ", displayRows=" + displayRows
+ ", udfs='" + udfs + '\''
+ ", showType='" + showType + '\''
+ ", connParams='" + connParams + '\''

33
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/BooleanUtils.java

@ -0,0 +1,33 @@
/*
* 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.common.utils;
public class BooleanUtils {
public static boolean isTrue(Boolean bool) {
if (bool == null) {
return false;
} else {
return bool;
}
}
public static boolean isNotTrue(Boolean bool) {
return !isTrue(bool);
}
}

34
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java

@ -257,6 +257,23 @@ public class OSUtils {
return users;
}
/**
* create user
*
* @param userName user name
*/
public static void createUserIfAbsent(String userName) {
// if not exists this user, then create
taskLoggerThreadLocal.set(taskLoggerThreadLocal.get());
if (!getUserList().contains(userName)) {
boolean isSuccess = createUser(userName);
String infoLog = String.format("create user %s %s", userName, isSuccess ? "success" : "fail");
LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog);
LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog);
}
taskLoggerThreadLocal.remove();
}
/**
* create user
*
@ -265,7 +282,7 @@ public class OSUtils {
*/
public static boolean createUser(String userName) {
try {
String userGroup = OSUtils.getGroup();
String userGroup = getGroup();
if (StringUtils.isEmpty(userGroup)) {
String errorLog = String.format("%s group does not exist for this operating system.", userGroup);
LoggerUtils.logError(Optional.ofNullable(logger), errorLog);
@ -304,7 +321,7 @@ public class OSUtils {
String infoLog2 = String.format("execute cmd : %s", cmd);
LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog2);
LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog2);
OSUtils.exeCmd(cmd);
exeCmd(cmd);
}
/**
@ -315,7 +332,6 @@ public class OSUtils {
* @throws IOException in case of an I/O error
*/
private static void createMacUser(String userName, String userGroup) throws IOException {
Optional<Logger> optionalLogger = Optional.ofNullable(logger);
Optional<Logger> optionalTaskLogger = Optional.ofNullable(taskLoggerThreadLocal.get());
@ -327,13 +343,13 @@ public class OSUtils {
String infoLog2 = String.format("create user command : %s", createUserCmd);
LoggerUtils.logInfo(optionalLogger, infoLog2);
LoggerUtils.logInfo(optionalTaskLogger, infoLog2);
OSUtils.exeCmd(createUserCmd);
exeCmd(createUserCmd);
String appendGroupCmd = String.format("sudo dseditgroup -o edit -a %s -t user %s", userName, userGroup);
String infoLog3 = String.format("append user to group : %s", appendGroupCmd);
LoggerUtils.logInfo(optionalLogger, infoLog3);
LoggerUtils.logInfo(optionalTaskLogger, infoLog3);
OSUtils.exeCmd(appendGroupCmd);
exeCmd(appendGroupCmd);
}
/**
@ -352,13 +368,13 @@ public class OSUtils {
String infoLog2 = String.format("execute create user command : %s", userCreateCmd);
LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog2);
LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog2);
OSUtils.exeCmd(userCreateCmd);
exeCmd(userCreateCmd);
String appendGroupCmd = String.format("net localgroup \"%s\" \"%s\" /add", userGroup, userName);
String infoLog3 = String.format("execute append user to group : %s", appendGroupCmd);
LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog3);
LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog3);
OSUtils.exeCmd(appendGroupCmd);
exeCmd(appendGroupCmd);
}
/**
@ -472,9 +488,9 @@ public class OSUtils {
*/
public static Boolean checkResource(double systemCpuLoad, double systemReservedMemory) {
// system load average
double loadAverage = OSUtils.loadAverage();
double loadAverage = loadAverage();
// system available physical memory
double availablePhysicalMemorySize = OSUtils.availablePhysicalMemorySize();
double availablePhysicalMemorySize = availablePhysicalMemorySize();
if (loadAverage > systemCpuLoad || availablePhysicalMemorySize < systemReservedMemory) {
logger.warn("load is too high or availablePhysicalMemorySize(G) is too low, it's availablePhysicalMemorySize(G):{},loadAvg:{}", availablePhysicalMemorySize, loadAverage);

14
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/PropertyUtils.java

@ -22,8 +22,6 @@ import static org.apache.dolphinscheduler.common.Constants.COMMON_PROPERTIES_PAT
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.ResUploadType;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
@ -51,7 +49,13 @@ public class PropertyUtils {
}
static {
String[] propertyFiles = new String[]{COMMON_PROPERTIES_PATH};
loadPropertyFile(COMMON_PROPERTIES_PATH);
}
/**
* init properties
*/
public static synchronized void loadPropertyFile(String... propertyFiles) {
for (String fileName : propertyFiles) {
InputStream fis = null;
try {
@ -196,7 +200,7 @@ public class PropertyUtils {
* @param defaultVal default value
* @return property value
*/
public double getDouble(String key, double defaultVal) {
public static double getDouble(String key, double defaultVal) {
String val = getString(key);
return val == null ? defaultVal : Double.parseDouble(val);
}
@ -229,7 +233,7 @@ public class PropertyUtils {
* @param <T> T
* @return get enum value
*/
public <T extends Enum<T>> T getEnum(String key, Class<T> type,
public static <T extends Enum<T>> T getEnum(String key, Class<T> type,
T defaultValue) {
String val = getString(key);
return val == null ? defaultValue : Enum.valueOf(type, val);

50
dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/ResInfo.java

@ -14,7 +14,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.common.utils;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.model.Server;
@ -38,8 +40,6 @@ public class ResInfo {
*/
private double loadAverage;
public ResInfo(){}
public ResInfo(double cpuUsage, double memoryUsage) {
this.cpuUsage = cpuUsage;
this.memoryUsage = memoryUsage;
@ -86,30 +86,48 @@ public class ResInfo {
return JSONUtils.toJsonString(resInfo);
}
/**
* parse heartbeat info for zk
* @param heartBeatInfo heartbeat info
* @return heartbeat info to Server
*/
public static Server parseHeartbeatForZKInfo(String heartBeatInfo) {
if (StringUtils.isEmpty(heartBeatInfo)) {
if (!isValidHeartbeatForZKInfo(heartBeatInfo)) {
return null;
}
String[] masterArray = heartBeatInfo.split(Constants.COMMA);
if(masterArray.length != Constants.HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH){
return null;
String[] parts = heartBeatInfo.split(Constants.COMMA);
Server server = new Server();
server.setResInfo(getResInfoJson(Double.parseDouble(parts[0]),
Double.parseDouble(parts[1]),
Double.parseDouble(parts[2])));
server.setCreateTime(DateUtils.stringToDate(parts[6]));
server.setLastHeartbeatTime(DateUtils.stringToDate(parts[7]));
//set process id
server.setId(Integer.parseInt(parts[9]));
return server;
}
/**
* is valid heartbeat info for zk
* @param heartBeatInfo heartbeat info
* @return heartbeat info is valid
*/
public static boolean isValidHeartbeatForZKInfo(String heartBeatInfo) {
if (StringUtils.isNotEmpty(heartBeatInfo)) {
String[] parts = heartBeatInfo.split(Constants.COMMA);
return parts.length == Constants.HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH
|| parts.length == Constants.HEARTBEAT_WITH_WEIGHT_FOR_ZOOKEEPER_INFO_LENGTH;
}
Server masterServer = new Server();
masterServer.setResInfo(getResInfoJson(Double.parseDouble(masterArray[0]),
Double.parseDouble(masterArray[1]),
Double.parseDouble(masterArray[2])));
masterServer.setCreateTime(DateUtils.stringToDate(masterArray[6]));
masterServer.setLastHeartbeatTime(DateUtils.stringToDate(masterArray[7]));
//set process id
masterServer.setId(Integer.parseInt(masterArray[9]));
return masterServer;
return false;
}
/**
* is new heartbeat info for zk with weight
* @param parts heartbeat info parts
* @return heartbeat info is new with weight
*/
public static boolean isNewHeartbeatWithWeight(String[] parts) {
return parts.length == Constants.HEARTBEAT_WITH_WEIGHT_FOR_ZOOKEEPER_INFO_LENGTH;
}
}

4
dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/task/DataxParametersTest.java

@ -27,7 +27,7 @@ public class DataxParametersTest {
/**
* jvm parameters
*/
public static final String JVM_EVN = " --jvm=\"-Xms%sG -Xmx%sG\" ";
public static final String JVM_PARAM = " --jvm=\"-Xms%sG -Xmx%sG\" ";
@Test
public void testLoadJvmEnv() {
@ -88,6 +88,6 @@ public class DataxParametersTest {
public String loadJvmEnvTest(DataxParameters dataXParameters) {
int xms = dataXParameters.getXms() < 1 ? 1 : dataXParameters.getXms();
int xmx = dataXParameters.getXmx() < 1 ? 1 : dataXParameters.getXmx();
return String.format(JVM_EVN, xms, xmx);
return String.format(JVM_PARAM, xms, xmx);
}
}

68
dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/task/SqlParametersTest.java

@ -0,0 +1,68 @@
/*
* 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.common.task;
import org.apache.dolphinscheduler.common.task.sql.SqlParameters;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
public class SqlParametersTest {
private final String type = "MYSQL";
private final String sql = "select * from t_ds_user";
private final String udfs = "test-udfs-1.0.0-SNAPSHOT.jar";
private final int datasource = 1;
private final int sqlType = 0;
private final Boolean sendEmail = true;
private final int displayRows = 10;
private final String showType = "TABLE";
private final String title = "sql test";
private final int groupId = 0;
@Test
public void testSqlParameters() {
SqlParameters sqlParameters = new SqlParameters();
Assert.assertTrue(CollectionUtils.isEmpty(sqlParameters.getResourceFilesList()));
sqlParameters.setType(type);
sqlParameters.setSql(sql);
sqlParameters.setUdfs(udfs);
sqlParameters.setDatasource(datasource);
sqlParameters.setSqlType(sqlType);
sqlParameters.setSendEmail(sendEmail);
sqlParameters.setDisplayRows(displayRows);
sqlParameters.setShowType(showType);
sqlParameters.setTitle(title);
sqlParameters.setGroupId(groupId);
Assert.assertEquals(type, sqlParameters.getType());
Assert.assertEquals(sql, sqlParameters.getSql());
Assert.assertEquals(udfs, sqlParameters.getUdfs());
Assert.assertEquals(datasource, sqlParameters.getDatasource());
Assert.assertEquals(sqlType, sqlParameters.getSqlType());
Assert.assertEquals(sendEmail, sqlParameters.getSendEmail());
Assert.assertEquals(displayRows, sqlParameters.getDisplayRows());
Assert.assertEquals(showType, sqlParameters.getShowType());
Assert.assertEquals(title, sqlParameters.getTitle());
Assert.assertEquals(groupId, sqlParameters.getGroupId());
Assert.assertTrue(sqlParameters.checkParameters());
}
}

16
dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/OSUtilsTest.java

@ -16,17 +16,19 @@
*/
package org.apache.dolphinscheduler.common.utils;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.dolphinscheduler.common.Constants;
import java.io.IOException;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
public class OSUtilsTest {
private static final Logger logger = LoggerFactory.getLogger(OSUtilsTest.class);
@ -75,6 +77,12 @@ public class OSUtilsTest {
}
}
@Test
public void createUserIfAbsent() {
OSUtils.createUserIfAbsent("test123");
Assert.assertTrue("create user test123 success", true);
}
@Test
public void testGetSudoCmd() {
String cmd = "kill -9 1234";

3
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/PluginDao.java

@ -19,6 +19,7 @@ package org.apache.dolphinscheduler.dao;
import static java.util.Objects.requireNonNull;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.dao.datasource.ConnectionFactory;
import org.apache.dolphinscheduler.dao.entity.PluginDefine;
import org.apache.dolphinscheduler.dao.mapper.PluginDefineMapper;
@ -64,7 +65,7 @@ public class PluginDao extends AbstractBaseDao {
requireNonNull(pluginDefine.getPluginType(), "pluginType is null");
List<PluginDefine> pluginDefineList = pluginDefineMapper.queryByNameAndType(pluginDefine.getPluginName(), pluginDefine.getPluginType());
if (pluginDefineList == null || pluginDefineList.size() == 0) {
if (CollectionUtils.isEmpty(pluginDefineList)) {
return pluginDefineMapper.insert(pluginDefine);
}
PluginDefine currPluginDefine = pluginDefineList.get(0);

23
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/TaskRecordDao.java

@ -14,27 +14,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import static org.apache.dolphinscheduler.common.Constants.DATASOURCE_PROPERTIES;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.TaskRecordStatus;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.ConnectionUtils;
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.TaskRecord;
import org.apache.dolphinscheduler.dao.utils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* task record dao
@ -44,8 +48,13 @@ public class TaskRecordDao {
private static Logger logger = LoggerFactory.getLogger(TaskRecordDao.class.getName());
static {
PropertyUtils.loadPropertyFile(DATASOURCE_PROPERTIES);
}
/**
* get task record flag
*
* @return whether startup taskrecord
*/
public static boolean getTaskRecordFlag() {

33
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/datasource/SpringConnectionFactory.java

@ -14,23 +14,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import static org.apache.dolphinscheduler.common.Constants.DATASOURCE_PROPERTIES;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.dao.utils.PropertyUtils;
import org.apache.dolphinscheduler.common.utils.PropertyUtils;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import java.util.Properties;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
@ -41,7 +40,12 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
/**
@ -53,9 +57,13 @@ public class SpringConnectionFactory {
private static final Logger logger = LoggerFactory.getLogger(SpringConnectionFactory.class);
static {
PropertyUtils.loadPropertyFile(DATASOURCE_PROPERTIES);
}
/**
* pagination interceptor
*
* @return pagination interceptor
*/
@Bean
@ -65,6 +73,7 @@ public class SpringConnectionFactory {
/**
* get the data source
*
* @return druid dataSource
*/
@Bean(destroyMethod = "")
@ -100,6 +109,7 @@ public class SpringConnectionFactory {
/**
* * get transaction manager
*
* @return DataSourceTransactionManager
*/
@Bean
@ -109,6 +119,7 @@ public class SpringConnectionFactory {
/**
* * get sql session factory
*
* @return sqlSessionFactory
* @throws Exception sqlSessionFactory exception
*/
@ -139,8 +150,8 @@ public class SpringConnectionFactory {
/**
* get sql session
*
* @return SqlSession
* @throws Exception
*/
@Bean
public SqlSession sqlSession() throws Exception {

7
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapper.java

@ -48,6 +48,13 @@ public interface AlertGroupMapper extends BaseMapper<AlertGroup> {
*/
List<AlertGroup> queryByGroupName(@Param("groupName") String groupName);
/**
* Judge whether the alert group exist
* @param groupName groupName
* @return if exist return true else return null
*/
Boolean existGroupName(@Param("groupName") String groupName);
/**
* query by userId
* @param userId userId

7
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapper.java

@ -44,4 +44,11 @@ public interface AlertPluginInstanceMapper extends BaseMapper<AlertPluginInstanc
List<AlertPluginInstance> queryByInstanceName(@Param("instanceName")String instanceName);
/**
*
* @param instanceName instanceName
* @return if exist return true else return null
*/
Boolean existInstanceName(@Param("instanceName") String instanceName);
}

7
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ProcessDefinitionMapper.java

@ -182,4 +182,11 @@ public interface ProcessDefinitionMapper extends BaseMapper<ProcessDefinition> {
*/
IPage<ProcessDefinitionLog> queryProcessDefinitionVersionsPaging(Page<ProcessDefinitionLog> page,
@Param("processDefinitionCode") Long processDefinitionCode);
/**
* query has associated definition by id and version
* @param processDefinitionId process definition id
* @param version version
* @return definition id
*/
Integer queryHasAssociatedDefinitionByIdAndVersion(@Param("processDefinitionId") int processDefinitionId, @Param("version") long version);
}

7
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/QueueMapper.java

@ -46,4 +46,11 @@ public interface QueueMapper extends BaseMapper<Queue> {
List<Queue> queryAllQueueList(@Param("queue") String queue,
@Param("queueName") String queueName);
/**
* check the target queue exist
* @param queue queue
* @param queueName queueName
* @return true if exist else return null
*/
Boolean existQueue(@Param("queue") String queue, @Param("queueName") String queueName);
}

52
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ResourceMapper.java

@ -14,15 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao.mapper;
import org.apache.dolphinscheduler.dao.entity.Resource;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
/**
* resource mapper interface
*/
@ -43,14 +46,10 @@ public interface ResourceMapper extends BaseMapper<Resource> {
* query resource list
* @param userId userId
* @param type type
* @param perm perm
* @return resource list
*/
List<Resource> queryResourceListAuthored(
@Param("userId") int userId,
@Param("type") int type,
@Param("perm") int perm);
List<Resource> queryResourceListAuthored(@Param("userId") int userId,
@Param("type") int type);
/**
* resource page
@ -59,20 +58,15 @@ public interface ResourceMapper extends BaseMapper<Resource> {
* @param id id
* @param type type
* @param searchVal searchVal
* @param resIds resIds
* @return resource page
*/
IPage<Resource> queryResourcePaging(IPage<Resource> page,
@Param("userId") int userId,
@Param("id") int id,
@Param("type") int type,
@Param("searchVal") String searchVal);
/**
* query Authed resource list
* @param userId userId
* @return resource list
*/
List<Resource> queryAuthorizedResourceList(@Param("userId") int userId);
@Param("searchVal") String searchVal,
@Param("resIds") List<Integer> resIds);
/**
* query resource except userId
@ -81,14 +75,6 @@ public interface ResourceMapper extends BaseMapper<Resource> {
*/
List<Resource> queryResourceExceptUserId(@Param("userId") int userId);
/**
* query tenant code by name
* @param resName resource name
* @param resType resource type
* @return tenant code
*/
String queryTenantCodeByResourceName(@Param("resName") String resName,@Param("resType") int resType);
/**
* list authorized resource
* @param userId userId
@ -98,7 +84,12 @@ public interface ResourceMapper extends BaseMapper<Resource> {
*/
<T> List<Resource> listAuthorizedResource(@Param("userId") int userId, @Param("resNames") T[] resNames);
/**
* list resources by id
* @param resIds resIds
* @return resource list
*/
List<Resource> queryResourceListById(@Param("resIds") List<Integer> resIds);
/**
* list authorized resource
@ -144,4 +135,15 @@ public interface ResourceMapper extends BaseMapper<Resource> {
* @return update num
*/
int batchUpdateResource(@Param("resourceList") List<Resource> resourceList);
/**
* check resource exist
* @param fullName full name
* @param userId userId
* @param type type
* @return true if exist else return null
*/
Boolean existResource(@Param("fullName") String fullName,
@Param("userId") int userId,
@Param("type") int type);
}

16
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/ResourceUserMapper.java

@ -14,17 +14,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao.mapper;
import org.apache.dolphinscheduler.dao.entity.ResourcesUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* resource user relation mapper interface
*/
public interface ResourceUserMapper extends BaseMapper<ResourcesUser> {
/**
* query resourcesId list by userId and perm
* @param userId userId
* @param perm perm
* @return resourcesId list result
*/
List<Integer> queryResourcesIdListByUserIdAndPerm(@Param("userId") int userId,
@Param("perm") int perm);
/**
* delete resource user relation
* @param userId userId

7
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/TenantMapper.java

@ -50,4 +50,11 @@ public interface TenantMapper extends BaseMapper<Tenant> {
*/
IPage<Tenant> queryTenantPaging(IPage<Tenant> page,
@Param("searchVal") String searchVal);
/**
* check tenant exist
* @param tenantCode tenantCode
* @return true if exist else return null
*/
Boolean existTenant(@Param("tenantCode") String tenantCode);
}

9
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/mapper/UserMapper.java

@ -100,7 +100,14 @@ public interface UserMapper extends BaseMapper<User> {
* @param queueName queue name
* @return user list
*/
List<User> queryUserListByQueue(@Param("queueName") String queueName);
List<User> queryUserListByQueue(@Param("queue") String queueName);
/**
* check the user exist
* @param queueName queue name
* @return true if exist else return null
*/
Boolean existUser(@Param("queue") String queue);
/**
* update user with old queue

162
dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/PropertyUtils.java

@ -1,162 +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.dao.utils;
import org.apache.dolphinscheduler.common.Constants;
import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* property utils
* single instance
*/
public class PropertyUtils {
/**
* logger
*/
private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);
private static final Properties properties = new Properties();
private static final PropertyUtils propertyUtils = new PropertyUtils();
private PropertyUtils(){
init();
}
/**
* init
*/
private void init(){
String[] propertyFiles = new String[]{Constants.DATASOURCE_PROPERTIES};
for (String fileName : propertyFiles) {
InputStream fis = null;
try {
fis = PropertyUtils.class.getResourceAsStream(fileName);
properties.load(fis);
} catch (IOException e) {
logger.error(e.getMessage(), e);
if (fis != null) {
IOUtils.closeQuietly(fis);
}
System.exit(1);
} finally {
IOUtils.closeQuietly(fis);
}
}
}
/**
* get property value
* @param key property name
* @return get string value
*/
public static String getString(String key) {
return properties.getProperty(key);
}
/**
* get property value
*
* @param key property name
* @param defaultVal default value
* @return property value
*/
public static String getString(String key, String defaultVal) {
String val = properties.getProperty(key.trim());
return val == null ? defaultVal : val;
}
/**
* get property value
* @param key property name
* @return get property int value , if key == null, then return -1
*/
public static int getInt(String key) {
return getInt(key, -1);
}
/**
* get property value
* @param key key
* @param defaultValue defaultValue
* @return get property int valueif key == null then return defaultValue
*/
public static int getInt(String key, int defaultValue) {
String value = getString(key);
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.info(e.getMessage(),e);
}
return defaultValue;
}
/**
* get property value
*
* @param key property name
* @return property value
*/
public static Boolean getBoolean(String key) {
String value = properties.getProperty(key.trim());
if(null != value){
return Boolean.parseBoolean(value);
}
return false;
}
/**
* get property value
*
* @param key property name
* @param defaultValue default value
* @return property value
*/
public static Boolean getBoolean(String key, boolean defaultValue) {
String value = properties.getProperty(key.trim());
if(null != value){
return Boolean.parseBoolean(value);
}
return defaultValue;
}
/**
* get property long value
* @param key key
* @param defaultVal default value
* @return property value
*/
public static long getLong(String key, long defaultVal) {
String val = getString(key);
return val == null ? defaultVal : Long.parseLong(val);
}
}

7
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapper.xml

@ -38,6 +38,13 @@
from t_ds_alertgroup
where group_name=#{groupName}
</select>
<select id="existGroupName" resultType="java.lang.Boolean">
select 1
from t_ds_alertgroup
where group_name=#{groupName} limit 1
</select>
<select id="queryByUserId" resultType="org.apache.dolphinscheduler.dao.entity.AlertGroup">
select
<include refid="baseSql"/>

6
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapper.xml

@ -43,4 +43,10 @@
where instance_name = #{instanceName}
</select>
<select id="existInstanceName" resultType="java.lang.Boolean">
select 1
from t_ds_alert_plugin_instance
where instance_name = #{instanceName} limit 1
</select>
</mapper>

7
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ProcessDefinitionMapper.xml

@ -173,4 +173,11 @@
set version = #{version}
where id = #{processDefinitionId}
</update>
<select id="queryHasAssociatedDefinitionByIdAndVersion" resultType="java.lang.Integer">
select id
from t_ds_process_definition
where id = #{processDefinitionId}
and version = #{version} limit 1
</select>
</mapper>

12
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/QueueMapper.xml

@ -43,5 +43,15 @@
and queue_name =#{queueName}
</if>
</select>
<select id="existQueue" resultType="java.lang.Boolean">
select 1 = 1
from t_ds_queue
where 1 = 1
<if test="queue != null and queue != ''">
and queue = #{queue}
</if>
<if test="queueName != null and queueName != ''">
and queue_name =#{queueName}
</if>
</select>
</mapper>

131
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ResourceMapper.xml

@ -18,90 +18,82 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.apache.dolphinscheduler.dao.mapper.ResourceMapper">
<sql id="baseSql">
id, alias, file_name, description, user_id, type, size, create_time, update_time,
pid, full_name, is_directory
</sql>
<sql id="baseSqlV2">
${alias}.id, ${alias}.alias, ${alias}.file_name, ${alias}.description, ${alias}.user_id, ${alias}.type, ${alias}.size, ${alias}.create_time, ${alias}.update_time,
${alias}.pid, ${alias}.full_name, ${alias}.is_directory
</sql>
<select id="queryResourceList" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where 1= 1
<if test="fullName != null and fullName != ''">
and full_name = #{fullName}
and r.full_name = #{fullName}
</if>
<if test="type != -1">
and type = #{type}
and r.type = #{type}
</if>
<if test="userId != 0">
and user_id = #{userId}
and r.user_id = #{userId}
</if>
</select>
<select id="queryResourceListAuthored" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where 1 = 1
<if test="type != -1">
and type=#{type}
</if>
<if test="userId != 0 and perm != 0">
and id in (select resources_id from t_ds_relation_resources_user where user_id=#{userId} and perm=#{perm}
union select id as resources_id from t_ds_resources where user_id=#{userId})
and r.type=#{type}
</if>
<if test="userId != 0 and perm == 0">
and id in (select resources_id from t_ds_relation_resources_user where user_id=#{userId}
union select id as resources_id from t_ds_resources where user_id=#{userId})
<if test="userId != 0">
and r.user_id=#{userId}
</if>
</select>
<select id="queryResourcePaging" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
d.id, d.alias, d.file_name, d.description, d.user_id, d.type, d.size, d.create_time, d.update_time,
d.pid, d.full_name, d.is_directory,
u.user_name as user_name
<include refid="baseSqlV2">
<property name="alias" value="d"/>
</include>
from t_ds_resources d
join t_ds_user u on d.user_id = u.id
where d.type=#{type} and d.pid=#{id}
<if test="userId != 0">
and d.id in (select resources_id from t_ds_relation_resources_user where user_id=#{userId}
union select id as resources_id from t_ds_resources where user_id=#{userId})
and (
<if test="resIds != null and resIds.size() > 0">
and d.id in
<foreach collection="resIds" item="i" open="(" close=") or" separator=",">
#{i}
</foreach>
</if>
d.user_id=#{userId} )
</if>
<if test="searchVal != null and searchVal != ''">
and d.alias like concat('%', #{searchVal}, '%')
</if>
order by d.update_time desc
</select>
<select id="queryAuthorizedResourceList" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
<select id="queryResourceExceptUserId" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r,t_ds_relation_resources_user rel
where r.id = rel.resources_id AND rel.user_id = #{userId} and perm=7
</select>
<select id="queryResourceExceptUserId" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
where user_id <![CDATA[ <> ]]> #{userId}
</select>
<select id="queryTenantCodeByResourceName" resultType="java.lang.String">
select tenant_code
from t_ds_tenant t, t_ds_user u, t_ds_resources res
where t.id = u.tenant_id and u.id = res.user_id and res.type=#{resType}
and res.full_name= #{resName}
from t_ds_resources r
where r.user_id <![CDATA[ <> ]]> #{userId}
</select>
<select id="listAuthorizedResource" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
where type=0
and id in (select resources_id from t_ds_relation_resources_user where user_id=#{userId} and perm=7
union select id as resources_id from t_ds_resources where user_id=#{userId})
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where r.type = 0
and r.user_id=#{userId}
<if test="resNames != null and resNames.length > 0">
and full_name in
<foreach collection="resNames" item="i" open="(" close=")" separator=",">
@ -109,12 +101,27 @@
</foreach>
</if>
</select>
<select id="queryResourceListById" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where 1 = 1
<if test="resIds != null and resIds.size() > 0">
and r.id in
<foreach collection="resIds" item="i" open="(" close=")" separator=",">
#{i}
</foreach>
</if>
</select>
<select id="listAuthorizedResourceById" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
where id in (select resources_id from t_ds_relation_resources_user where user_id=#{userId} and perm=7
union select id as resources_id from t_ds_resources where user_id=#{userId})
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where r.user_id=#{userId}
<if test="resIds != null and resIds.length > 0">
and id in
<foreach collection="resIds" item="i" open="(" close=")" separator=",">
@ -138,10 +145,12 @@
<select id="queryResource" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
where type = #{type}
and full_name = #{fullName}
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where r.type = #{type}
and r.full_name = #{fullName}
</select>
<update id="batchUpdateResource" parameterType="java.util.List">
@ -159,11 +168,21 @@
<select id="listResourceByIds" resultType="org.apache.dolphinscheduler.dao.entity.Resource">
select
<include refid="baseSql"/>
from t_ds_resources
where id in
<include refid="baseSqlV2">
<property name="alias" value="r"/>
</include>
from t_ds_resources r
where r.id in
<foreach collection="resIds" item="i" open="(" close=")" separator=",">
#{i}
</foreach>
</select>
<select id="existResource" resultType="java.lang.Boolean">
select 1
from t_ds_resources
where full_name = #{fullName}
and type = #{type}
and user_id = #{userId} limit 1
</select>
</mapper>

14
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/ResourceUserMapper.xml

@ -18,6 +18,20 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.apache.dolphinscheduler.dao.mapper.ResourceUserMapper">
<select id="queryResourcesIdListByUserIdAndPerm" resultType="java.lang.Integer">
select
resources_id
from t_ds_relation_resources_user rel
where 1 = 1
<if test="userId != 0 and perm != 0">
and rel.user_id=#{userId} and rel.perm=#{perm}
</if>
<if test="userId != 0 and perm == 0">
and rel.user_id=#{userId}
</if>
</select>
<delete id="deleteResourceUser">
delete
from t_ds_relation_resources_user

5
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/TenantMapper.xml

@ -54,4 +54,9 @@
</if>
order by t.update_time desc
</select>
<select id="existTenant" resultType="java.lang.Boolean">
select 1
from t_ds_tenant
where tenant_code = #{tenantCode} limit 1
</select>
</mapper>

7
dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml

@ -103,7 +103,12 @@
select
<include refid="baseSql"/>
from t_ds_user
where queue = #{queueName}
where queue = #{queue}
</select>
<select id="existUser" resultType="java.lang.Boolean">
select 1
from t_ds_user
where queue = #{queue} limit 1
</select>
<update id="updateUserQueue" parameterType="java.lang.String">
update t_ds_user

9
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/AlertGroupMapperTest.java

@ -31,6 +31,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -161,6 +162,14 @@ public class AlertGroupMapperTest {
compareAlertGroups(alertGroupMap, alertGroupList);
}
@Test
public void testExistGroupName() {
String groupName = "testGroup";
createAlertGroups(1, groupName);
Assert.assertTrue(alertGroupMapper.existGroupName(groupName));
}
/**
* test query all group list
*/

8
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/AlertPluginInstanceMapperTest.java

@ -67,6 +67,14 @@ public class AlertPluginInstanceMapperTest {
AlertGroup alertGroup = testAlertGroupList.get(0);
}
@Test
public void testExistInstanceName() {
String instanceName = "test_instance";
Assert.assertNull(alertPluginInstanceMapper.existInstanceName(instanceName));
createAlertPluginInstance();
Assert.assertTrue(alertPluginInstanceMapper.existInstanceName(instanceName));
}
/**
* insert
*

19
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/QueueMapperTest.java

@ -14,12 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao.mapper;
package org.apache.dolphinscheduler.dao.mapper;
import org.apache.dolphinscheduler.common.utils.BooleanUtils;
import org.apache.dolphinscheduler.dao.entity.Queue;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -29,8 +35,6 @@ import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@ -123,4 +127,13 @@ public class QueueMapperTest {
queues = queueMapper.queryAllQueueList(null, queue.getQueueName());
Assert.assertNotEquals(queues.size(), 0);
}
@Test
public void existQueue() {
Assert.assertNull(queueMapper.existQueue("queue", null));
Assert.assertNull(queueMapper.existQueue(null, "queue"));
Queue queue = insertOne();
Assert.assertTrue(BooleanUtils.isTrue(queueMapper.existQueue(queue.getQueue(), null)));
Assert.assertTrue(BooleanUtils.isTrue(queueMapper.existQueue(null, queue.getQueueName())));
}
}

68
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/ResourceMapperTest.java

@ -14,18 +14,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dolphinscheduler.dao.mapper;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.ResourceType;
import org.apache.dolphinscheduler.common.enums.UserType;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.dao.entity.Resource;
import org.apache.dolphinscheduler.dao.entity.ResourcesUser;
import org.apache.dolphinscheduler.dao.entity.Tenant;
import org.apache.dolphinscheduler.dao.entity.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -35,15 +46,8 @@ import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@RunWith(SpringRunner.class)
@SpringBootTest
@ -238,14 +242,16 @@ public class ResourceMapperTest {
0,
-1,
resource.getType().ordinal(),
""
"",
new ArrayList<>()
);
IPage<Resource> resourceIPage1 = resourceMapper.queryResourcePaging(
page,
1110,
-1,
resource.getType().ordinal(),
""
"",
null
);
Assert.assertEquals(resourceIPage.getTotal(), 0);
Assert.assertEquals(resourceIPage1.getTotal(), 0);
@ -259,7 +265,8 @@ public class ResourceMapperTest {
public void testQueryResourceListAuthored() {
Resource resource = insertOne();
List<Resource> resources = resourceMapper.queryAuthorizedResourceList(resource.getUserId());
List<Integer> resIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(resource.getUserId(), Constants.AUTHORIZE_WRITABLE_PERM);
List<Resource> resources = CollectionUtils.isEmpty(resIds) ? new ArrayList<>() : resourceMapper.queryResourceListById(resIds);
ResourcesUser resourcesUser = new ResourcesUser();
@ -268,7 +275,8 @@ public class ResourceMapperTest {
resourcesUser.setPerm(Constants.AUTHORIZE_WRITABLE_PERM);
resourceUserMapper.insert(resourcesUser);
List<Resource> resources1 = resourceMapper.queryAuthorizedResourceList(1110);
List<Integer> resIds1 = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(1110, Constants.AUTHORIZE_WRITABLE_PERM);
List<Resource> resources1 = CollectionUtils.isEmpty(resIds1) ? new ArrayList<>() : resourceMapper.queryResourceListById(resIds1);
Assert.assertEquals(0, resources.size());
Assert.assertNotEquals(0, resources1.size());
@ -282,7 +290,8 @@ public class ResourceMapperTest {
public void testQueryAuthorizedResourceList() {
Resource resource = insertOne();
List<Resource> resources = resourceMapper.queryAuthorizedResourceList(resource.getUserId());
List<Integer> resIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(resource.getUserId(), Constants.AUTHORIZE_WRITABLE_PERM);
List<Resource> resources = CollectionUtils.isEmpty(resIds) ? new ArrayList<>() : resourceMapper.queryResourceListById(resIds);
resourceMapper.deleteById(resource.getId());
Assert.assertEquals(0, resources.size());
@ -306,7 +315,6 @@ public class ResourceMapperTest {
@Test
public void testQueryTenantCodeByResourceName() {
Tenant tenant = new Tenant();
tenant.setTenantCode("ut tenant code for resource");
int tenantInsertStatus = tenantMapper.insert(tenant);
@ -324,7 +332,6 @@ public class ResourceMapperTest {
Assert.fail("insert user data error");
}
Resource resource = insertOne();
resource.setUserId(user.getId());
int userUpdateStatus = resourceMapper.updateById(resource);
@ -332,12 +339,13 @@ public class ResourceMapperTest {
Assert.fail("update user data error");
}
String resource1 = resourceMapper.queryTenantCodeByResourceName(
resource.getFullName(), ResourceType.FILE.ordinal()
);
List<Resource> resourceList = resourceMapper.queryResource(resource.getFullName(), ResourceType.FILE.ordinal());
int resourceUserId = resourceList.get(0).getUserId();
User resourceUser = userMapper.selectById(resourceUserId);
Tenant resourceTenant = tenantMapper.selectById(resourceUser.getTenantId());
Assert.assertEquals("ut tenant code for resource", resource1);
Assert.assertEquals("ut tenant code for resource", resourceTenant.getTenantCode());
}
@ -358,7 +366,6 @@ public class ResourceMapperTest {
Assert.assertEquals(generalUser2.getId(), resource.getUserId());
Assert.assertFalse(resources.stream().map(t -> t.getFullName()).collect(toList()).containsAll(Arrays.asList(resNames)));
// authorize object unauthorizedResource to generalUser
createResourcesUser(unauthorizedResource, generalUser2);
List<Resource> authorizedResources = resourceMapper.listAuthorizedResource(generalUser2.getId(), resNames);
@ -391,10 +398,10 @@ public class ResourceMapperTest {
Resource resource = createResource(generalUser1);
createResourcesUser(resource, generalUser2);
List<Resource> resourceList = resourceMapper.queryResourceListAuthored(generalUser2.getId(), ResourceType.FILE.ordinal(), 0);
List<Resource> resourceList = resourceMapper.queryResourceListAuthored(generalUser2.getId(), ResourceType.FILE.ordinal());
Assert.assertNotNull(resourceList);
resourceList = resourceMapper.queryResourceListAuthored(generalUser2.getId(), ResourceType.FILE.ordinal(), 4);
resourceList = resourceMapper.queryResourceListAuthored(generalUser2.getId(), ResourceType.FILE.ordinal());
Assert.assertFalse(resourceList.contains(resource));
}
@ -413,4 +420,15 @@ public class ResourceMapperTest {
Assert.fail("batch update resource data error");
}
}
@Test
public void existResourceTest() {
String fullName = "/ut-resource";
int userId = 111;
int type = ResourceType.FILE.getCode();
Assert.assertNull(resourceMapper.existResource(fullName, userId, type));
insertOne();
Assert.assertTrue(resourceMapper.existResource(fullName, userId, type));
}
}

10
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/TenantMapperTest.java

@ -54,6 +54,7 @@ public class TenantMapperTest {
Tenant tenant = new Tenant();
tenant.setCreateTime(new Date());
tenant.setUpdateTime(new Date());
tenant.setTenantCode("test_code");
tenantMapper.insert(tenant);
return tenant;
}
@ -122,6 +123,8 @@ public class TenantMapperTest {
Tenant tenant = insertOne();
tenant.setTenantCode("ut code");
tenantMapper.updateById(tenant);
List<Tenant> tenantList = tenantMapper.queryByTenantCode("ut code");
Assert.assertEquals(1, tenantList.size());
}
/**
@ -146,4 +149,11 @@ public class TenantMapperTest {
Assert.assertNotEquals(tenantIPage.getTotal(), 0);
}
public void testExistTenant() {
String tenantCode = "test_code";
Assert.assertNull(tenantMapper.existTenant(tenantCode));
insertOne();
Assert.assertTrue(tenantMapper.existTenant(tenantCode));
}
}

10
dolphinscheduler-dao/src/test/java/org/apache/dolphinscheduler/dao/mapper/UserMapperTest.java

@ -74,6 +74,8 @@ public class UserMapperTest {
user.setCreateTime(new Date());
user.setTenantId(1);
user.setUpdateTime(new Date());
user.setQueueName("test_queue");
user.setQueue("queue");
userMapper.insert(user);
return user;
}
@ -312,4 +314,12 @@ public class UserMapperTest {
Assert.assertEquals(userToken, user);
}
@Test
public void testExistUser() {
String queueName = "queue";
Assert.assertNull(userMapper.existUser(queueName));
insertOne();
Assert.assertTrue(userMapper.existUser(queueName));
}
}

143
dolphinscheduler-remote/src/main/java/org/apache/dolphinscheduler/remote/utils/Host.java

@ -20,8 +20,6 @@ package org.apache.dolphinscheduler.remote.utils;
import static org.apache.dolphinscheduler.common.Constants.COLON;
import java.io.Serializable;
import java.util.Objects;
import java.util.StringJoiner;
/**
* server address
@ -43,21 +41,6 @@ public class Host implements Serializable {
*/
private int port;
/**
* weight
*/
private int weight;
/**
* startTime
*/
private long startTime;
/**
* workGroup
*/
private String workGroup;
public Host() {
}
@ -67,21 +50,11 @@ public class Host implements Serializable {
this.address = ip + COLON + port;
}
public Host(String ip, int port, int weight, long startTime) {
this.ip = ip;
this.port = port;
this.address = ip + COLON + port;
this.weight = getWarmUpWeight(weight, startTime);
this.startTime = startTime;
}
public Host(String ip, int port, int weight, long startTime, String workGroup) {
this.ip = ip;
this.port = port;
this.address = ip + COLON + port;
this.weight = getWarmUpWeight(weight, startTime);
this.workGroup = workGroup;
this.startTime = startTime;
public Host(String address) {
String[] parts = splitAddress(address);
this.ip = parts[0];
this.port = Integer.parseInt(parts[1]);
this.address = address;
}
public String getAddress() {
@ -89,6 +62,9 @@ public class Host implements Serializable {
}
public void setAddress(String address) {
String[] parts = splitAddress(address);
this.ip = parts[0];
this.port = Integer.parseInt(parts[1]);
this.address = address;
}
@ -101,22 +77,6 @@ public class Host implements Serializable {
this.address = ip + COLON + port;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public int getPort() {
return port;
}
@ -126,12 +86,15 @@ public class Host implements Serializable {
this.address = ip + COLON + port;
}
public String getWorkGroup() {
return workGroup;
}
public void setWorkGroup(String workGroup) {
this.workGroup = workGroup;
/**
* address convert host
*
* @param address address
* @return host
*/
public static Host of(String address) {
String[] parts = splitAddress(address);
return new Host(parts[0], Integer.parseInt(parts[1]));
}
/**
@ -140,37 +103,15 @@ public class Host implements Serializable {
* @param address address
* @return host
*/
public static Host of(String address) {
public static String[] splitAddress(String address) {
if (address == null) {
throw new IllegalArgumentException("Host : address is null.");
}
String[] parts = address.split(COLON);
if (parts.length < 2) {
if (parts.length != 2) {
throw new IllegalArgumentException(String.format("Host : %s illegal.", address));
}
Host host = null;
if (parts.length == 2) {
host = new Host(parts[0], Integer.parseInt(parts[1]));
}
if (parts.length == 4) {
host = new Host(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Long.parseLong(parts[3]));
}
return host;
}
/**
* generate host string
* @param address address
* @param weight weight
* @param startTime startTime
* @return address:weight:startTime
*/
public static String generate(String address, int weight, long startTime) {
StringJoiner stringJoiner = new StringJoiner(COLON);
stringJoiner.add(address)
.add(String.valueOf(weight))
.add(String.valueOf(startTime));
return stringJoiner.toString();
return parts;
}
/**
@ -181,54 +122,16 @@ public class Host implements Serializable {
*/
public static Boolean isOldVersion(String address) {
String[] parts = address.split(COLON);
return parts.length != 2 && parts.length != 3;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Host host = (Host) o;
return Objects.equals(getAddress(), host.getAddress());
}
@Override
public int hashCode() {
return Objects.hash(getAddress());
return parts.length != 2;
}
@Override
public String toString() {
return "Host{"
+ "address='" + address + '\''
+ ", weight=" + weight
+ ", startTime=" + startTime
+ ", workGroup='" + workGroup + '\''
+ ", ip='" + ip + '\''
+ ", port=" + port
+ '}';
}
/**
* warm up
*/
private int getWarmUpWeight(int weight, long startTime) {
long uptime = System.currentTimeMillis() - startTime;
//If the warm-up is not over, reduce the weight
if (uptime > 0 && uptime < Constants.WARM_UP_TIME) {
return (int) (weight * ((float) uptime / Constants.WARM_UP_TIME));
}
return weight;
}
/**
* get address and weight
*
* @return address:weight
*/
public String getAddressAndWeight() {
return address + COLON + weight;
}
}

11
dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/NettyRemotingClientTest.java

@ -17,7 +17,6 @@
package org.apache.dolphinscheduler.remote;
import io.netty.channel.Channel;
import org.apache.dolphinscheduler.remote.command.Command;
import org.apache.dolphinscheduler.remote.command.CommandType;
import org.apache.dolphinscheduler.remote.command.Ping;
@ -28,20 +27,22 @@ import org.apache.dolphinscheduler.remote.future.InvokeCallback;
import org.apache.dolphinscheduler.remote.future.ResponseFuture;
import org.apache.dolphinscheduler.remote.processor.NettyRequestProcessor;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Assert;
import org.junit.Test;
import io.netty.channel.Channel;
/**
* netty remote client test
*/
public class NettyRemotingClientTest {
/**
* test sned sync
* test send sync
*/
@Test
public void testSendSync() {

10
dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/ResponseFutureTest.java → dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/future/ResponseFutureTest.java

@ -15,20 +15,20 @@
* limitations under the License.
*/
package org.apache.dolphinscheduler.remote;
package org.apache.dolphinscheduler.remote.command.future;
import org.apache.dolphinscheduler.remote.future.InvokeCallback;
import org.apache.dolphinscheduler.remote.future.ResponseFuture;
import org.apache.dolphinscheduler.remote.utils.NamedThreadFactory;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
public class ResponseFutureTest {
@Test
@ -51,7 +51,7 @@ public class ResponseFutureTest {
ResponseFuture future = new ResponseFuture(1, 2000, invokeCallback, null);
try {
latch.await(5000, TimeUnit.MILLISECONDS);
Assert.assertTrue(ResponseFuture.getFuture(1) == null);
Assert.assertNull(ResponseFuture.getFuture(1));
} catch (InterruptedException e) {
e.printStackTrace();
}

8
dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/RemoveTaskLogRequestCommandTest.java → dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/log/RemoveTaskLogRequestCommandTest.java

@ -15,14 +15,14 @@
* limitations under the License.
*/
package org.apache.dolphinscheduler.remote;
package org.apache.dolphinscheduler.remote.command.log;
import junit.framework.Assert;
import org.apache.dolphinscheduler.remote.command.Command;
import org.apache.dolphinscheduler.remote.command.log.RemoveTaskLogRequestCommand;
import org.apache.dolphinscheduler.remote.command.log.RemoveTaskLogResponseCommand;
import org.junit.Test;
import junit.framework.Assert;
public class RemoveTaskLogRequestCommandTest {
@Test

7
dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/RemoveTaskLogResponseCommandTest.java → dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/command/log/RemoveTaskLogResponseCommandTest.java

@ -15,13 +15,14 @@
* limitations under the License.
*/
package org.apache.dolphinscheduler.remote;
package org.apache.dolphinscheduler.remote.command.log;
import junit.framework.Assert;
import org.apache.dolphinscheduler.remote.command.Command;
import org.apache.dolphinscheduler.remote.command.log.RemoveTaskLogRequestCommand;
import org.junit.Test;
import junit.framework.Assert;
public class RemoveTaskLogResponseCommandTest {
@Test

23
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/utils/HostTest.java → dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/utils/HostTest.java

@ -15,9 +15,7 @@
* limitations under the License.
*/
package org.apache.dolphinscheduler.server.utils;
import org.apache.dolphinscheduler.remote.utils.Host;
package org.apache.dolphinscheduler.remote.utils;
import org.junit.Assert;
import org.junit.Test;
@ -27,26 +25,13 @@ import org.junit.Test;
*/
public class HostTest {
@Test
public void testHostWarmUp() {
Host host = Host.of(("192.158.2.2:22:100:" + (System.currentTimeMillis() - 60 * 5 * 1000)));
Assert.assertEquals(50, host.getWeight());
host = Host.of(("192.158.2.2:22:100:" + (System.currentTimeMillis() - 60 * 10 * 1000)));
Assert.assertEquals(100, host.getWeight());
}
@Test
public void testHost() {
Host host = Host.of("192.158.2.2:22");
Assert.assertEquals(22, host.getPort());
host.setAddress("127.0.0.1:8888");
Assert.assertEquals("127.0.0.1", host.getIp());
Assert.assertEquals(8888, host.getPort());
}
@Test
public void testGenerate() {
String address = "192.158.2.2:22";
int weight = 100;
long startTime = System.currentTimeMillis();
String generateHost = Host.generate(address, weight, startTime);
Assert.assertEquals(address + ":" + weight + ":" + startTime, generateHost);
}
}

5
dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/NettyUtilTest.java → dolphinscheduler-remote/src/test/java/org/apache/dolphinscheduler/remote/utils/NettyUtilTest.java

@ -15,12 +15,10 @@
* limitations under the License.
*/
package org.apache.dolphinscheduler.remote;
package org.apache.dolphinscheduler.remote.utils;
import static org.apache.dolphinscheduler.remote.utils.Constants.OS_NAME;
import org.apache.dolphinscheduler.remote.utils.NettyUtils;
import org.junit.Assert;
import org.junit.Test;
@ -31,7 +29,6 @@ import io.netty.channel.epoll.Epoll;
*/
public class NettyUtilTest {
@Test
public void testUserEpoll() {
if (OS_NAME.toLowerCase().contains("linux") && Epoll.isAvailable()) {

44
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/CommonHostManager.java

@ -17,26 +17,32 @@
package org.apache.dolphinscheduler.server.master.dispatch.host;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.ResInfo;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.server.master.dispatch.context.ExecutionContext;
import org.apache.dolphinscheduler.server.master.dispatch.enums.ExecutorType;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.HostWorker;
import org.apache.dolphinscheduler.server.registry.ZookeeperNodeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dolphinscheduler.server.registry.ZookeeperRegistryCenter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
/**
* round robin host manager
*/
public abstract class CommonHostManager implements HostManager {
private final Logger logger = LoggerFactory.getLogger(CommonHostManager.class);
/**
* zookeeper registry center
*/
@Autowired
protected ZookeeperRegistryCenter registryCenter;
/**
* zookeeperNodeManager
@ -53,13 +59,12 @@ public abstract class CommonHostManager implements HostManager {
public Host select(ExecutionContext context) {
Host host = new Host();
Collection<String> nodes = null;
/**
* executor type
*/
String workerGroup = context.getWorkerGroup();
// executor type
ExecutorType executorType = context.getExecutorType();
switch (executorType) {
case WORKER:
nodes = zookeeperNodeManager.getWorkerGroupNodes(context.getWorkerGroup());
nodes = zookeeperNodeManager.getWorkerGroupNodes(workerGroup);
break;
case CLIENT:
break;
@ -67,21 +72,26 @@ public abstract class CommonHostManager implements HostManager {
throw new IllegalArgumentException("invalid executorType : " + executorType);
}
if(CollectionUtils.isEmpty(nodes)){
if (nodes == null || nodes.isEmpty()) {
return host;
}
List<Host> candidateHosts = new ArrayList<>(nodes.size());
List<HostWorker> candidateHosts = new ArrayList<>();
nodes.forEach(node -> {
Host nodeHost=Host.of(node);
nodeHost.setWorkGroup(context.getWorkerGroup());
candidateHosts.add(nodeHost);
String workerGroupPath = registryCenter.getWorkerGroupPath(workerGroup);
String heartbeat = registryCenter.getRegisterOperator().get(workerGroupPath + "/" + node);
int hostWeight = Constants.DEFAULT_WORKER_HOST_WEIGHT;
if (StringUtils.isNotEmpty(heartbeat)) {
String[] parts = heartbeat.split(Constants.COMMA);
if (ResInfo.isNewHeartbeatWithWeight(parts)) {
hostWeight = Integer.parseInt(parts[10]);
}
}
candidateHosts.add(HostWorker.of(node, hostWeight, workerGroup));
});
return select(candidateHosts);
}
protected abstract Host select(Collection<Host> nodes);
protected abstract HostWorker select(Collection<HostWorker> nodes);
public void setZookeeperNodeManager(ZookeeperNodeManager zookeeperNodeManager) {
this.zookeeperNodeManager = zookeeperNodeManager;

40
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/LowerWeightHostManager.java

@ -19,20 +19,20 @@ package org.apache.dolphinscheduler.server.master.dispatch.host;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.ResInfo;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.remote.utils.NamedThreadFactory;
import org.apache.dolphinscheduler.server.master.dispatch.context.ExecutionContext;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.HostWeight;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.HostWorker;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.LowerWeightRoundRobin;
import org.apache.dolphinscheduler.server.registry.ZookeeperRegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@ -40,8 +40,11 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dolphinscheduler.common.Constants.COMMA;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* round robin host manager
@ -50,12 +53,6 @@ public class LowerWeightHostManager extends CommonHostManager {
private final Logger logger = LoggerFactory.getLogger(LowerWeightHostManager.class);
/**
* zookeeper registry center
*/
@Autowired
private ZookeeperRegistryCenter registryCenter;
/**
* round robin host manager
*/
@ -112,7 +109,7 @@ public class LowerWeightHostManager extends CommonHostManager {
}
@Override
public Host select(Collection<Host> nodes) {
public HostWorker select(Collection<HostWorker> nodes) {
throw new UnsupportedOperationException("not support");
}
@ -150,21 +147,20 @@ public class LowerWeightHostManager extends CommonHostManager {
Set<HostWeight> hostWeights = new HashSet<>(nodes.size());
for (String node : nodes) {
String heartbeat = registryCenter.getRegisterOperator().get(workerGroupPath + "/" + node);
if(StringUtils.isNotEmpty(heartbeat)
&& heartbeat.split(COMMA).length == Constants.HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH){
String[] parts = heartbeat.split(COMMA);
if (ResInfo.isValidHeartbeatForZKInfo(heartbeat)) {
String[] parts = heartbeat.split(Constants.COMMA);
int status = Integer.parseInt(parts[8]);
if (status == Constants.ABNORMAL_NODE_STATUS) {
logger.warn("load is too high or availablePhysicalMemorySize(G) is too low, it's availablePhysicalMemorySize(G):{},loadAvg:{}",
Double.parseDouble(parts[3]) , Double.parseDouble(parts[2]));
continue;
}
double cpu = Double.parseDouble(parts[0]);
double memory = Double.parseDouble(parts[1]);
double loadAverage = Double.parseDouble(parts[2]);
HostWeight hostWeight = new HostWeight(Host.of(node), cpu, memory, loadAverage);
long startTime = DateUtils.stringToDate(parts[6]).getTime();
int weight = ResInfo.isNewHeartbeatWithWeight(parts) ? Integer.parseInt(parts[10]) : Constants.DEFAULT_WORKER_HOST_WEIGHT;
HostWeight hostWeight = new HostWeight(HostWorker.of(node, weight, workerGroup), cpu, memory, loadAverage, startTime);
hostWeights.add(hostWeight);
}
}

9
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/RandomHostManager.java

@ -17,13 +17,11 @@
package org.apache.dolphinscheduler.server.master.dispatch.host;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.HostWorker;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.RandomSelector;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.Selector;
import java.util.Collection;
/**
* round robin host manager
*/
@ -32,7 +30,7 @@ public class RandomHostManager extends CommonHostManager {
/**
* selector
*/
private final Selector<Host> selector;
private final RandomSelector selector;
/**
* set round robin
@ -42,7 +40,8 @@ public class RandomHostManager extends CommonHostManager {
}
@Override
public Host select(Collection<Host> nodes) {
public HostWorker select(Collection<HostWorker> nodes) {
return selector.select(nodes);
}
}

7
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/RoundRobinHostManager.java

@ -17,9 +17,8 @@
package org.apache.dolphinscheduler.server.master.dispatch.host;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.HostWorker;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.RoundRobinSelector;
import org.apache.dolphinscheduler.server.master.dispatch.host.assign.Selector;
import java.util.Collection;
@ -32,7 +31,7 @@ public class RoundRobinHostManager extends CommonHostManager {
/**
* selector
*/
private final Selector<Host> selector;
private final RoundRobinSelector selector;
/**
* set round robin
@ -42,7 +41,7 @@ public class RoundRobinHostManager extends CommonHostManager {
}
@Override
public Host select(Collection<Host> nodes) {
public HostWorker select(Collection<HostWorker> nodes) {
return selector.select(nodes);
}

44
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWeight.java

@ -31,57 +31,55 @@ public class HostWeight {
private final int LOAD_AVERAGE_FACTOR = 70;
private final Host host;
private final HostWorker hostWorker;
private final double weight;
private double currentWeight;
public HostWeight(Host host, double cpu, double memory, double loadAverage) {
this.weight = getWeight(cpu, memory, loadAverage, host);
this.host = host;
this.currentWeight = weight;
}
public double getCurrentWeight() {
return currentWeight;
public HostWeight(HostWorker hostWorker, double cpu, double memory, double loadAverage, long startTime) {
this.hostWorker = hostWorker;
this.weight = calculateWeight(cpu, memory, loadAverage, startTime);
this.currentWeight = this.weight;
}
public double getWeight() {
return weight;
}
public double getCurrentWeight() {
return currentWeight;
}
public void setCurrentWeight(double currentWeight) {
this.currentWeight = currentWeight;
}
public HostWorker getHostWorker() {
return hostWorker;
}
public Host getHost() {
return host;
return (Host)hostWorker;
}
@Override
public String toString() {
return "HostWeight{"
+ "host=" + host
+ "hostWorker=" + hostWorker
+ ", weight=" + weight
+ ", currentWeight=" + currentWeight
+ '}';
}
private double getWeight(double cpu, double memory, double loadAverage, Host host) {
double calculateWeight = cpu * CPU_FACTOR + memory * MEMORY_FACTOR + loadAverage * LOAD_AVERAGE_FACTOR;
return getWarmUpWeight(host, calculateWeight);
}
/**
* If the warm-up is not over, add the weight
*/
private double getWarmUpWeight(Host host, double weight) {
long startTime = host.getStartTime();
private double calculateWeight(double cpu, double memory, double loadAverage, long startTime) {
double calculatedWeight = cpu * CPU_FACTOR + memory * MEMORY_FACTOR + loadAverage * LOAD_AVERAGE_FACTOR;
long uptime = System.currentTimeMillis() - startTime;
if (uptime > 0 && uptime < Constants.WARM_UP_TIME) {
return weight * Constants.WARM_UP_TIME / uptime;
// If the warm-up is not over, add the weight
return calculatedWeight * Constants.WARM_UP_TIME / uptime;
}
return weight;
return calculatedWeight;
}
}

77
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWorker.java

@ -0,0 +1,77 @@
/*
* 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.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
/**
* host worker
*/
public class HostWorker extends Host {
/**
* host weight
*/
private int hostWeight;
/**
* worker group
*/
private String workerGroup;
public HostWorker(String ip, int port, int hostWeight, String workerGroup) {
super(ip, port);
this.hostWeight = hostWeight;
this.workerGroup = workerGroup;
}
public HostWorker(String address, int hostWeight, String workerGroup) {
super(address);
this.hostWeight = hostWeight;
this.workerGroup = workerGroup;
}
public int getHostWeight() {
return hostWeight;
}
public void setHostWeight(int hostWeight) {
this.hostWeight = hostWeight;
}
public String getWorkerGroup() {
return workerGroup;
}
public void setWorkerGroup(String workerGroup) {
this.workerGroup = workerGroup;
}
public static HostWorker of(String address, int hostWeight, String workerGroup) {
return new HostWorker(address, hostWeight, workerGroup);
}
@Override
public String toString() {
return "Host{"
+ "hostWeight=" + hostWeight
+ ", workerGroup='" + workerGroup + '\''
+ '}';
}
}

14
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RandomSelector.java

@ -17,8 +17,6 @@
package org.apache.dolphinscheduler.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@ -27,20 +25,20 @@ import java.util.concurrent.ThreadLocalRandom;
/**
* random selector
*/
public class RandomSelector extends AbstractSelector<Host> {
public class RandomSelector extends AbstractSelector<HostWorker> {
@Override
public Host doSelect(final Collection<Host> source) {
public HostWorker doSelect(final Collection<HostWorker> source) {
List<Host> hosts = new ArrayList<>(source);
List<HostWorker> hosts = new ArrayList<>(source);
int size = hosts.size();
int[] weights = new int[size];
int totalWeight = 0;
int index = 0;
for (Host host : hosts) {
totalWeight += host.getWeight();
weights[index] = host.getWeight();
for (HostWorker host : hosts) {
totalWeight += host.getHostWeight();
weights[index] = host.getHostWeight();
index++;
}

27
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RoundRobinSelector.java

@ -16,20 +16,21 @@
*/
package org.apache.dolphinscheduler.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
/**
* Smooth Weight Round Robin
*/
@Service
public class RoundRobinSelector extends AbstractSelector<Host> {
public class RoundRobinSelector extends AbstractSelector<HostWorker> {
private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> workGroupWeightMap = new ConcurrentHashMap<>();
@ -69,12 +70,11 @@ public class RoundRobinSelector extends AbstractSelector<Host> {
}
@Override
public Host doSelect(Collection<Host> source) {
public HostWorker doSelect(Collection<HostWorker> source) {
List<Host> hosts = new ArrayList<>(source);
String key = hosts.get(0).getWorkGroup();
List<HostWorker> hosts = new ArrayList<>(source);
String key = hosts.get(0).getWorkerGroup();
ConcurrentMap<String, WeightedRoundRobin> map = workGroupWeightMap.get(key);
if (map == null) {
workGroupWeightMap.putIfAbsent(key, new ConcurrentHashMap<>());
@ -84,13 +84,13 @@ public class RoundRobinSelector extends AbstractSelector<Host> {
int totalWeight = 0;
long maxCurrent = Long.MIN_VALUE;
long now = System.currentTimeMillis();
Host selectedHost = null;
HostWorker selectedHost = null;
WeightedRoundRobin selectWeightRoundRobin = null;
for (Host host : hosts) {
String workGroupHost = host.getWorkGroup() + host.getAddress();
for (HostWorker host : hosts) {
String workGroupHost = host.getWorkerGroup() + host.getAddress();
WeightedRoundRobin weightedRoundRobin = map.get(workGroupHost);
int weight = host.getWeight();
int weight = host.getHostWeight();
if (weight < 0) {
weight = 0;
}
@ -117,7 +117,6 @@ public class RoundRobinSelector extends AbstractSelector<Host> {
totalWeight += weight;
}
if (!updateLock.get() && hosts.size() != map.size() && updateLock.compareAndSet(false, true)) {
try {
ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<>(map);

4
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/registry/MasterRegistry.java

@ -98,8 +98,8 @@ public class MasterRegistry {
});
int masterHeartbeatInterval = masterConfig.getMasterHeartbeatInterval();
HeartBeatTask heartBeatTask = new HeartBeatTask(startTime,
masterConfig.getMasterReservedMemory(),
masterConfig.getMasterMaxCpuloadAvg(),
masterConfig.getMasterReservedMemory(),
Sets.newHashSet(getMasterPath()),
Constants.MASTER_PREFIX,
zookeeperRegistryCenter);
@ -132,9 +132,7 @@ public class MasterRegistry {
* get local address
*/
private String getLocalAddress() {
return NetUtils.getAddr(masterConfig.getListenPort());
}
/**

13
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterExecThread.java

@ -562,7 +562,7 @@ public class MasterExecThread implements Runnable {
private void setProcessGlobal(TaskNode taskNode, TaskInstance taskInstance) {
String globalParams = this.processInstance.getGlobalParams();
if (StringUtils.isNotEmpty(globalParams)) {
Map<String, String> globalMap = getGlobalParamMap(globalParams);
Map<String, String> globalMap = processService.getGlobalParamMap(globalParams);
if (globalMap != null && globalMap.size() != 0) {
setGlobalMapToTask(taskNode, taskInstance, globalMap);
}
@ -591,17 +591,6 @@ public class MasterExecThread implements Runnable {
}
}
public Map<String, String> getGlobalParamMap(String globalParams) {
List<Property> propList;
Map<String,String> globalParamMap = new HashMap<>();
if (StringUtils.isNotEmpty(globalParams)) {
propList = JSONUtils.toList(globalParams, Property.class);
globalParamMap = propList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue));
}
return globalParamMap;
}
private void submitPostNode(String parentNodeName) {
Set<String> submitTaskNodeList = DagHelper.parsePostNodes(parentNodeName, skipTaskNodeList, dag, completeTaskList);
List<TaskInstance> taskInstances = new ArrayList<>();

28
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/registry/HeartBeatTask.java

@ -38,8 +38,9 @@ public class HeartBeatTask implements Runnable {
private final Logger logger = LoggerFactory.getLogger(HeartBeatTask.class);
private String startTime;
private double reservedMemory;
private double maxCpuloadAvg;
private double reservedMemory;
private int hostWeight; // worker host weight
private Set<String> heartBeatPaths;
private String serverType;
private ZookeeperRegistryCenter zookeeperRegistryCenter;
@ -48,23 +49,38 @@ public class HeartBeatTask implements Runnable {
protected IStoppable stoppable = null;
public HeartBeatTask(String startTime,
double reservedMemory,
double maxCpuloadAvg,
double reservedMemory,
Set<String> heartBeatPaths,
String serverType,
ZookeeperRegistryCenter zookeeperRegistryCenter) {
this.startTime = startTime;
this.reservedMemory = reservedMemory;
this.maxCpuloadAvg = maxCpuloadAvg;
this.reservedMemory = reservedMemory;
this.heartBeatPaths = heartBeatPaths;
this.serverType = serverType;
this.zookeeperRegistryCenter = zookeeperRegistryCenter;
}
public HeartBeatTask(String startTime,
double maxCpuloadAvg,
double reservedMemory,
int hostWeight,
Set<String> heartBeatPaths,
String serverType,
ZookeeperRegistryCenter zookeeperRegistryCenter) {
this.startTime = startTime;
this.maxCpuloadAvg = maxCpuloadAvg;
this.reservedMemory = reservedMemory;
this.hostWeight = hostWeight;
this.heartBeatPaths = heartBeatPaths;
this.serverType = serverType;
this.zookeeperRegistryCenter = zookeeperRegistryCenter;
}
@Override
public void run() {
try {
// check dead or not in zookeeper
for (String heartBeatPath : heartBeatPaths) {
if (zookeeperRegistryCenter.checkIsDeadServer(heartBeatPath, serverType)) {
@ -96,6 +112,10 @@ public class HeartBeatTask implements Runnable {
builder.append(status).append(COMMA);
// save process id
builder.append(OSUtils.getProcessID());
// worker host weight
if (Constants.WORKER_PREFIX.equals(serverType)) {
builder.append(Constants.COMMA).append(hostWeight);
}
for (String heartBeatPath : heartBeatPaths) {
zookeeperRegistryCenter.getRegisterOperator().update(heartBeatPath, builder.toString());

16
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/config/WorkerConfig.java

@ -35,8 +35,8 @@ public class WorkerConfig {
@Value("${worker.heartbeat.interval:10}")
private int workerHeartbeatInterval;
@Value("${worker.fetch.task.num:3}")
private int workerFetchTaskNum;
@Value("${worker.tenant.auto.create:false}")
private boolean workerTenantAutoCreate;
@Value("${worker.max.cpuload.avg:-1}")
private int workerMaxCpuloadAvg;
@ -88,12 +88,12 @@ public class WorkerConfig {
this.workerHeartbeatInterval = workerHeartbeatInterval;
}
public int getWorkerFetchTaskNum() {
return workerFetchTaskNum;
public boolean getWorkerTenantAutoCreate() {
return workerTenantAutoCreate;
}
public void setWorkerFetchTaskNum(int workerFetchTaskNum) {
this.workerFetchTaskNum = workerFetchTaskNum;
public void setWorkerTenantAutoCreate(boolean workerTenantAutoCreate) {
this.workerTenantAutoCreate = workerTenantAutoCreate;
}
public double getWorkerReservedMemory() {
@ -119,8 +119,8 @@ public class WorkerConfig {
return hostWeight;
}
public void setHostWeight(int weight) {
this.hostWeight = weight;
public void setHostWeight(int hostWeight) {
this.hostWeight = hostWeight;
}
public String getAlertListenHost() {

4
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/processor/TaskExecuteProcessor.java

@ -25,6 +25,7 @@ import org.apache.dolphinscheduler.common.utils.FileUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.common.utils.LoggerUtils;
import org.apache.dolphinscheduler.common.utils.NetUtils;
import org.apache.dolphinscheduler.common.utils.OSUtils;
import org.apache.dolphinscheduler.common.utils.Preconditions;
import org.apache.dolphinscheduler.remote.command.Command;
import org.apache.dolphinscheduler.remote.command.CommandType;
@ -146,6 +147,9 @@ public class TaskExecuteProcessor implements NettyRequestProcessor {
FileUtils.taskLoggerThreadLocal.set(taskLogger);
try {
FileUtils.createWorkDirIfAbsent(execLocalPath);
if (workerConfig.getWorkerTenantAutoCreate()) {
OSUtils.createUserIfAbsent(taskExecutionContext.getTenantCode());
}
} catch (Throwable ex) {
String errorLog = String.format("create execLocalPath : %s", execLocalPath);
LoggerUtils.logError(Optional.of(logger), errorLog, ex);

24
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/registry/WorkerRegistry.java

@ -24,7 +24,6 @@ import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.NetUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.remote.utils.NamedThreadFactory;
import org.apache.dolphinscheduler.server.registry.HeartBeatTask;
import org.apache.dolphinscheduler.server.registry.ZookeeperRegistryCenter;
@ -34,6 +33,7 @@ import org.apache.curator.framework.state.ConnectionState;
import java.util.Date;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ -120,12 +120,13 @@ public class WorkerRegistry {
logger.info("worker node : {} registry to ZK {} successfully", address, workerZKPath);
}
HeartBeatTask heartBeatTask = new HeartBeatTask(this.startTime,
this.workerConfig.getWorkerReservedMemory(),
this.workerConfig.getWorkerMaxCpuloadAvg(),
HeartBeatTask heartBeatTask = new HeartBeatTask(startTime,
workerConfig.getWorkerMaxCpuloadAvg(),
workerConfig.getWorkerReservedMemory(),
workerConfig.getHostWeight(),
workerZkPaths,
Constants.WORKER_PREFIX,
this.zookeeperRegistryCenter);
zookeeperRegistryCenter);
this.heartBeatExecutor.scheduleAtFixedRate(heartBeatTask, workerHeartbeatInterval, workerHeartbeatInterval, TimeUnit.SECONDS);
logger.info("worker node : {} heartbeat interval {} s", address, workerHeartbeatInterval);
@ -150,22 +151,19 @@ public class WorkerRegistry {
*/
public Set<String> getWorkerZkPaths() {
Set<String> workerZkPaths = Sets.newHashSet();
String address = getLocalAddress();
String workerZkPathPrefix = this.zookeeperRegistryCenter.getWorkerPath();
int weight = workerConfig.getHostWeight();
long workerStartTime = System.currentTimeMillis();
for (String workGroup : this.workerGroups) {
StringBuilder workerZkPathBuilder = new StringBuilder(100);
workerZkPathBuilder.append(workerZkPathPrefix).append(SLASH);
StringJoiner workerZkPathJoiner = new StringJoiner(SLASH);
workerZkPathJoiner.add(workerZkPathPrefix);
if (StringUtils.isEmpty(workGroup)) {
workGroup = DEFAULT_WORKER_GROUP;
}
// trim and lower case is need
workerZkPathBuilder.append(workGroup.trim().toLowerCase()).append(SLASH);
workerZkPathBuilder.append(Host.generate(address, weight, workerStartTime));
workerZkPaths.add(workerZkPathBuilder.toString());
workerZkPathJoiner.add(workGroup.trim().toLowerCase());
workerZkPathJoiner.add(address);
workerZkPaths.add(workerZkPathJoiner.toString());
}
return workerZkPaths;
}

10
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/datax/DataxTask.java

@ -81,15 +81,15 @@ public class DataxTask extends AbstractTask {
/**
* jvm parameters
*/
public static final String JVM_EVN = " --jvm=\"-Xms%sG -Xmx%sG\" ";
public static final String JVM_PARAM = " --jvm=\"-Xms%sG -Xmx%sG\" ";
/**
* python process(datax only supports version 2.7 by default)
*/
private static final String DATAX_PYTHON = "python2.7";
/**
* datax home path
* datax path
*/
private static final String DATAX_HOME_EVN = "${DATAX_HOME}";
private static final String DATAX_PATH = "${DATAX_HOME}/bin/datax.py";
/**
* datax channel count
*/
@ -396,7 +396,7 @@ public class DataxTask extends AbstractTask {
StringBuilder sbr = new StringBuilder();
sbr.append(DATAX_PYTHON);
sbr.append(" ");
sbr.append(DATAX_HOME_EVN);
sbr.append(DATAX_PATH);
sbr.append(" ");
sbr.append(loadJvmEnv(dataXParameters));
sbr.append(jobConfigFilePath);
@ -424,7 +424,7 @@ public class DataxTask extends AbstractTask {
public String loadJvmEnv(DataxParameters dataXParameters) {
int xms = dataXParameters.getXms() < 1 ? 1 : dataXParameters.getXms();
int xmx = dataXParameters.getXmx() < 1 ? 1 : dataXParameters.getXmx();
return String.format(JVM_EVN, xms, xmx);
return String.format(JVM_PARAM, xms, xmx);
}
/**

1
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/shell/ShellTask.java

@ -106,6 +106,7 @@ public class ShellTask extends AbstractTask {
setAppIds(commandExecuteResult.getAppIds());
setProcessId(commandExecuteResult.getProcessId());
setResult(shellCommandExecutor.getTaskResultString());
setVarPool(shellCommandExecutor.getVarPool());
} catch (Exception e) {
logger.error("shell task error", e);
setExitStatusCode(Constants.EXIT_CODE_FAILURE);

28
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/task/sql/SqlTask.java

@ -149,13 +149,13 @@ public class SqlTask extends AbstractTask {
logger);
// execute sql task
executeFuncAndSql(mainSqlBinds, preStatementSqlBinds, postStatementSqlBinds, createFuncs, sqlParameters.getLocalParams());
executeFuncAndSql(mainSqlBinds, preStatementSqlBinds, postStatementSqlBinds, createFuncs);
setExitStatusCode(Constants.EXIT_CODE_SUCCESS);
} catch (Exception e) {
setExitStatusCode(Constants.EXIT_CODE_FAILURE);
logger.error("sql task error", e);
logger.error("sql task error: {}", e.toString());
throw e;
}
}
@ -238,8 +238,7 @@ public class SqlTask extends AbstractTask {
public void executeFuncAndSql(SqlBinds mainSqlBinds,
List<SqlBinds> preStatementsBinds,
List<SqlBinds> postStatementsBinds,
List<String> createFuncs,
List<Property> properties) {
List<String> createFuncs) throws Exception {
Connection connection = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
@ -268,15 +267,15 @@ public class SqlTask extends AbstractTask {
} else if (sqlParameters.getSqlType() == SqlType.NON_QUERY.ordinal()) {
// non query statement
String updateResult = String.valueOf(stmt.executeUpdate());
result = setNonQuerySqlReturn(updateResult, properties);
result = setNonQuerySqlReturn(updateResult, sqlParameters.getLocalParams());
}
postSql(connection, postStatementsBinds);
this.setResultString(result);
} catch (Exception e) {
logger.error("execute sql error", e);
throw new RuntimeException("execute sql error");
logger.error("execute sql error: {}", e.getMessage());
throw e;
} finally {
close(resultSet, stmt, connection);
}
@ -319,12 +318,19 @@ public class SqlTask extends AbstractTask {
rowCount++;
}
String result = JSONUtils.toJsonString(resultJSONArray);
logger.debug("execute sql : {}", result);
try {
logger.debug("execute sql result : {}", result);
int displayRows = sqlParameters.getDisplayRows() > 0 ? sqlParameters.getDisplayRows() : Constants.DEFAULT_DISPLAY_ROWS;
displayRows = Math.min(displayRows, resultJSONArray.size());
logger.info("display sql result {} rows as follows:", displayRows);
for (int i = 0; i < displayRows; i++) {
String row = JSONUtils.toJsonString(resultJSONArray.get(i));
logger.info("row {} : {}", i + 1, row);
}
if (sqlParameters.getSendEmail() == null || sqlParameters.getSendEmail()) {
sendAttachment(sqlParameters.getGroupId(), StringUtils.isNotEmpty(sqlParameters.getTitle()) ? sqlParameters.getTitle() : taskExecutionContext.getTaskName() + " query result sets",
JSONUtils.toJsonString(resultJSONArray));
} catch (Exception e) {
logger.warn("sql task sendAttachment error! msg : {} ", e.getMessage());
}
return result;
}

2
dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/zk/ZKMasterClient.java

@ -28,7 +28,6 @@ import org.apache.dolphinscheduler.common.utils.NetUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import org.apache.dolphinscheduler.dao.entity.ProcessInstance;
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.apache.dolphinscheduler.server.builder.TaskExecutionContextBuilder;
import org.apache.dolphinscheduler.server.entity.TaskExecutionContext;
import org.apache.dolphinscheduler.server.master.MasterServer;
@ -308,7 +307,6 @@ public class ZKMasterClient extends AbstractZKClient {
* @throws Exception exception
*/
private void failoverWorker(String workerHost, boolean needCheckWorkerAlive) throws Exception {
workerHost = Host.of(workerHost).getAddress();
logger.info("start worker[{}] failover ...", workerHost);
List<TaskInstance> needFailoverTaskInstanceList = processService.queryNeedFailoverTaskInstances(workerHost);
for (TaskInstance taskInstance : needFailoverTaskInstanceList) {

3
dolphinscheduler-server/src/main/resources/worker.properties

@ -21,6 +21,9 @@
# worker heartbeat interval
#worker.heartbeat.interval=10
# worker tenant auto create
#worker.tenant.auto.create=false
# only less than cpu avg load, worker server can work. default value -1: the number of cpu cores * 2
#worker.max.cpuload.avg=-1

43
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/HostWorkerTest.java

@ -0,0 +1,43 @@
/*
* 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.server.master.dispatch.host.assign;
import org.junit.Assert;
import org.junit.Test;
public class HostWorkerTest {
@Test
public void testHostWorker1() {
HostWorker hostWorker = new HostWorker("192.158.2.2", 11, 20, "default");
Assert.assertEquals("192.158.2.2", hostWorker.getIp());
Assert.assertEquals(11, hostWorker.getPort());
Assert.assertEquals(20, hostWorker.getHostWeight());
Assert.assertEquals("default", hostWorker.getWorkerGroup());
}
@Test
public void testHostWorker2() {
HostWorker hostWorker = HostWorker.of("192.158.2.2:22", 80, "default");
Assert.assertEquals("192.158.2.2", hostWorker.getIp());
Assert.assertEquals(22, hostWorker.getPort());
Assert.assertEquals(80, hostWorker.getHostWeight());
Assert.assertEquals("default", hostWorker.getWorkerGroup());
}
}

22
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/LowerWeightRoundRobinTest.java

@ -17,24 +17,20 @@
package org.apache.dolphinscheduler.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
public class LowerWeightRoundRobinTest {
@Test
public void testSelect() {
Collection<HostWeight> sources = new ArrayList<>();
sources.add(new HostWeight(Host.of("192.158.2.1:11:100:" + (System.currentTimeMillis() - 60 * 8 * 1000)), 0.06, 0.44, 3.84));
sources.add(new HostWeight(Host.of("192.158.2.2:22:100:" + (System.currentTimeMillis() - 60 * 5 * 1000)), 0.06, 0.56, 3.24));
sources.add(new HostWeight(Host.of("192.158.2.3:33:100:" + (System.currentTimeMillis() - 60 * 2 * 1000)), 0.06, 0.80, 3.15));
sources.add(new HostWeight(HostWorker.of("192.158.2.1:11", 100, "default"), 0.06, 0.44, 3.84, System.currentTimeMillis() - 60 * 8 * 1000));
sources.add(new HostWeight(HostWorker.of("192.158.2.2:22", 100, "default"), 0.06, 0.56, 3.24, System.currentTimeMillis() - 60 * 5 * 1000));
sources.add(new HostWeight(HostWorker.of("192.158.2.3:33", 100, "default"), 0.06, 0.80, 3.15, System.currentTimeMillis() - 60 * 2 * 1000));
LowerWeightRoundRobin roundRobin = new LowerWeightRoundRobin();
HostWeight result;
@ -55,10 +51,10 @@ public class LowerWeightRoundRobinTest {
@Test
public void testWarmUpSelect() {
Collection<HostWeight> sources = new ArrayList<>();
sources.add(new HostWeight(Host.of("192.158.2.1:11:100:" + (System.currentTimeMillis() - 60 * 8 * 1000)), 0.06, 0.44, 3.84));
sources.add(new HostWeight(Host.of("192.158.2.2:22:100:" + (System.currentTimeMillis() - 60 * 5 * 1000)), 0.06, 0.44, 3.84));
sources.add(new HostWeight(Host.of("192.158.2.3:33:100:" + (System.currentTimeMillis() - 60 * 3 * 1000)), 0.06, 0.44, 3.84));
sources.add(new HostWeight(Host.of("192.158.2.4:33:100:" + (System.currentTimeMillis() - 60 * 11 * 1000)), 0.06, 0.44, 3.84));
sources.add(new HostWeight(HostWorker.of("192.158.2.1:11", 100, "default"), 0.06, 0.44, 3.84, System.currentTimeMillis() - 60 * 8 * 1000));
sources.add(new HostWeight(HostWorker.of("192.158.2.2:22", 100, "default"), 0.06, 0.44, 3.84, System.currentTimeMillis() - 60 * 5 * 1000));
sources.add(new HostWeight(HostWorker.of("192.158.2.3:33", 100, "default"), 0.06, 0.44, 3.84, System.currentTimeMillis() - 60 * 3 * 1000));
sources.add(new HostWeight(HostWorker.of("192.158.2.4:33", 100, "default"), 0.06, 0.44, 3.84, System.currentTimeMillis() - 60 * 11 * 1000));
LowerWeightRoundRobin roundRobin = new LowerWeightRoundRobin();
HostWeight result;

10
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RandomSelectorTest.java

@ -17,14 +17,11 @@
package org.apache.dolphinscheduler.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
/**
* random selector
*/
@ -39,15 +36,14 @@ public class RandomSelectorTest {
@Test
public void testSelect1() {
RandomSelector selector = new RandomSelector();
Host result = selector.select(Arrays.asList(new Host("192.168.1.1", 80, 100, System.currentTimeMillis()), new Host("192.168.1.2", 80, 20, System.currentTimeMillis())));
HostWorker result = selector.select(Arrays.asList(new HostWorker("192.168.1.1:11", 100, "default"), new HostWorker("192.168.1.2:22", 80, "default")));
Assert.assertNotNull(result);
}
@Test
public void testSelect() {
RandomSelector selector = new RandomSelector();
Host result = selector.select(Arrays.asList(new Host("192.168.1.1", 80, 100, System.currentTimeMillis()), new Host("192.168.1.1", 80, 20, System.currentTimeMillis())));
HostWorker result = selector.select(Arrays.asList(new HostWorker("192.168.1.1", 11, 100, "default"), new HostWorker("192.168.1.2:", 22, 20, "default")));
Assert.assertNotNull(result);
}
}

36
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/dispatch/host/assign/RoundRobinSelectorTest.java

@ -17,14 +17,12 @@
package org.apache.dolphinscheduler.server.master.dispatch.host.assign;
import org.apache.dolphinscheduler.remote.utils.Host;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
/**
* round robin selector
*/
@ -39,18 +37,16 @@ public class RoundRobinSelectorTest {
@Test
public void testSelect1() {
RoundRobinSelector selector = new RoundRobinSelector();
// dismiss of server warm-up time
long startTime = System.currentTimeMillis() - 60 * 10 * 1000;
List<Host> hostOneList = Arrays.asList(
new Host("192.168.1.1", 80, 20, startTime, "kris"),
new Host("192.168.1.2", 80, 10, startTime, "kris"));
List<Host> hostTwoList = Arrays.asList(
new Host("192.168.1.1", 80, 20, startTime, "kris"),
new Host("192.168.1.2", 80, 10, startTime, "kris"),
new Host("192.168.1.3", 80, 10, startTime, "kris"));
Host result;
List<HostWorker> hostOneList = Arrays.asList(
new HostWorker("192.168.1.1", 80, 20, "kris"),
new HostWorker("192.168.1.2", 80, 10, "kris"));
List<HostWorker> hostTwoList = Arrays.asList(
new HostWorker("192.168.1.1", 80, 20, "kris"),
new HostWorker("192.168.1.2", 80, 10, "kris"),
new HostWorker("192.168.1.3", 80, 10, "kris"));
HostWorker result;
result = selector.select(hostOneList);
Assert.assertEquals("192.168.1.1", result.getIp());
@ -93,17 +89,15 @@ public class RoundRobinSelectorTest {
result = selector.select(hostOneList);
Assert.assertEquals("192.168.1.1", result.getIp());
}
@Test
public void testWarmUpRoundRobinSelector() {
public void testWeightRoundRobinSelector() {
RoundRobinSelector selector = new RoundRobinSelector();
Host result;
HostWorker result;
result = selector.select(
Arrays.asList(new Host("192.168.1.1", 80, 20, System.currentTimeMillis() - 60 * 1000 * 2, "kris"), new Host("192.168.1.2", 80, 10, System.currentTimeMillis() - 60 * 1000 * 10, "kris")));
Arrays.asList(new HostWorker("192.168.1.1", 11, 20, "kris"), new HostWorker("192.168.1.2", 22, 80, "kris")));
Assert.assertEquals("192.168.1.2", result.getIp());
}
}

3
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/master/registry/MasterRegistryTest.java

@ -19,6 +19,7 @@ package org.apache.dolphinscheduler.server.master.registry;
import static org.apache.dolphinscheduler.common.Constants.HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH;
import org.apache.dolphinscheduler.common.utils.NetUtils;
import org.apache.dolphinscheduler.remote.utils.Constants;
import org.apache.dolphinscheduler.server.master.config.MasterConfig;
import org.apache.dolphinscheduler.server.registry.ZookeeperRegistryCenter;
@ -59,7 +60,7 @@ public class MasterRegistryTest {
masterRegistry.registry();
String masterPath = zookeeperRegistryCenter.getMasterPath();
TimeUnit.SECONDS.sleep(masterConfig.getMasterHeartbeatInterval() + 2); //wait heartbeat info write into zk node
String masterNodePath = masterPath + "/" + (Constants.LOCAL_ADDRESS + ":" + masterConfig.getListenPort());
String masterNodePath = masterPath + "/" + (NetUtils.getAddr(Constants.LOCAL_ADDRESS, masterConfig.getListenPort()));
String heartbeat = zookeeperRegistryCenter.getRegisterOperator().get(masterNodePath);
Assert.assertEquals(HEARTBEAT_FOR_ZOOKEEPER_INFO_LENGTH, heartbeat.split(",").length);
masterRegistry.unRegistry();

6
dolphinscheduler-server/src/test/java/org/apache/dolphinscheduler/server/registry/DependencyConfig.java

@ -30,6 +30,7 @@ import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapMapper;
import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper;
import org.apache.dolphinscheduler.dao.mapper.ProjectMapper;
import org.apache.dolphinscheduler.dao.mapper.ResourceMapper;
import org.apache.dolphinscheduler.dao.mapper.ResourceUserMapper;
import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper;
import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper;
import org.apache.dolphinscheduler.dao.mapper.TenantMapper;
@ -130,6 +131,11 @@ public class DependencyConfig {
return Mockito.mock(ResourceMapper.class);
}
@Bean
public ResourceUserMapper resourceUserMapper() {
return Mockito.mock(ResourceUserMapper.class);
}
@Bean
public ErrorCommandMapper errorCommandMapper() {
return Mockito.mock(ErrorCommandMapper.class);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save