From 8493aa8209b7a47745bd753f1e943ed617a25401 Mon Sep 17 00:00:00 2001 From: dailidong Date: Fri, 8 May 2020 16:08:08 +0800 Subject: [PATCH 01/10] simplify common config (#2613) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * update README about DolphinScheduler * Update issue templates * update * regularize api pom xml update rpc maven compile to 1.8 * regularize api pom xml * change commons.lang3.StringUtils to common.utils.StringUtils * update pom.xml * update * correct equals method * jasper-runtime is needed when api server start * jasper-runtime jar is needed when api server start * combine logback config of master/worker/alert/api server to one logback.xml * remove tomcat runtime jar * add UT * add license * remove jasper-runtime jar, not need anymore * sovle jar conflict, remove servlet-api 2.5 jar * remove servlet 2.5 * add embedded database h2 and update embedded zookeeper * delete logs * add license * change log level to INFO * simplify and optimize config * add development state * simplify common config Co-authored-by: lidongdai Co-authored-by: dailidong --- .../src/main/resources/common.properties | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/dolphinscheduler-common/src/main/resources/common.properties b/dolphinscheduler-common/src/main/resources/common.properties index d066f7b6b7..3852c310b1 100644 --- a/dolphinscheduler-common/src/main/resources/common.properties +++ b/dolphinscheduler-common/src/main/resources/common.properties @@ -19,22 +19,22 @@ resource.storage.type=NONE # resource store on HDFS/S3 path, resource file will store to this hadoop hdfs path, self configuration, please make sure the directory exists on hdfs and have read write permissions。"/dolphinscheduler" is recommended -resource.upload.path=/dolphinscheduler +#resource.upload.path=/dolphinscheduler # user data local directory path, please make sure the directory exists and have read write permissions #data.basedir.path=/tmp/dolphinscheduler # whether kerberos starts -hadoop.security.authentication.startup.state=false +#hadoop.security.authentication.startup.state=false # java.security.krb5.conf path -java.security.krb5.conf.path=/opt/krb5.conf +#java.security.krb5.conf.path=/opt/krb5.conf # login user from keytab username -login.user.keytab.username=hdfs-mycluster@ESZ.COM +#login.user.keytab.username=hdfs-mycluster@ESZ.COM # loginUserFromKeytab path -login.user.keytab.path=/opt/hdfs.headless.keytab +#login.user.keytab.path=/opt/hdfs.headless.keytab #resource.view.suffixs #resource.view.suffixs=txt,log,sh,conf,cfg,py,java,sql,hql,xml,properties @@ -46,18 +46,18 @@ hdfs.root.user=hdfs fs.defaultFS=hdfs://mycluster:8020 # if resource.storage.type=S3,s3 endpoint -fs.s3a.endpoint=http://192.168.199.91:9010 +#fs.s3a.endpoint=http://192.168.199.91:9010 # if resource.storage.type=S3,s3 access key -fs.s3a.access.key=A3DXS30FO22544RE +#fs.s3a.access.key=A3DXS30FO22544RE # if resource.storage.type=S3,s3 secret key -fs.s3a.secret.key=OloCLq3n+8+sdPHUhJ21XrSxTC+JK +#fs.s3a.secret.key=OloCLq3n+8+sdPHUhJ21XrSxTC+JK # if not use hadoop resourcemanager, please keep default value; if resourcemanager HA enable, please type the HA ips ; if resourcemanager is single, make this value empty yarn.resourcemanager.ha.rm.ids=192.168.xx.xx,192.168.xx.xx -# if resourcemanager HA enable or not use resourcemanager, please keep the default value; If resourcemanager is single, you only need to replace ark1 to actual resourcemanager hostname. +# If resourcemanager HA enable or not use resourcemanager, please keep the default value; If resourcemanager is single, you only need to replace ark1 to actual resourcemanager hostname. yarn.application.status.address=http://ark1:8088/ws/v1/cluster/apps/%s # system env path From a5b053643766ba646306bb6e351d60b3fbe4ebe8 Mon Sep 17 00:00:00 2001 From: xingchun-chen <55787491+xingchun-chen@users.noreply.github.com> Date: Fri, 8 May 2020 18:49:43 +0800 Subject: [PATCH 02/10] modify soft_version 1.2.2 to 1.3.0 (#2642) Co-authored-by: chenxingchun <438044805@qq.com> --- sql/soft_version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql/soft_version b/sql/soft_version index d2d61a7e8e..589268e6fe 100644 --- a/sql/soft_version +++ b/sql/soft_version @@ -1 +1 @@ -1.2.2 \ No newline at end of file +1.3.0 \ No newline at end of file From cb5285384efc2fdbaecf129eb4404095eb8ef419 Mon Sep 17 00:00:00 2001 From: s751167520 <751167520@qq.com> Date: Sun, 10 May 2020 23:05:12 +0800 Subject: [PATCH 03/10] Fix some code specification issues (#2482) * Fix some code specification issues * Pre-compile regular expressions to improve efficiency and solve concurrency problems * Solve the nullpoint problem that Object.equals may bring * Modify if else structure, add {} to improve code readability Co-Authored-By: daili * Update ResourceTreeVisitor.java re-run test process Co-authored-by: daili Co-authored-by: dailidong --- .../visitor/ResourceTreeVisitor.java | 2 + .../api/service/ResourcesService.java | 6 +- .../common/task/datax/DataxParameters.java | 4 +- .../common/utils/OSUtils.java | 11 ++- .../utils/process/ProcessBuilderForWin32.java | 86 ++++++++++++------ .../process/ProcessEnvironmentForWin32.java | 38 +++++++- .../utils/process/ProcessImplForWin32.java | 89 +++++++++++++------ .../dao/entity/ProcessInstanceMap.java | 20 +++-- .../dolphinscheduler/dao/entity/Queue.java | 16 +++- .../dolphinscheduler/dao/entity/Session.java | 20 +++-- .../dolphinscheduler/dao/entity/Tenant.java | 8 +- .../dao/utils/MysqlPerformance.java | 8 +- .../server/utils/ProcessUtils.java | 12 ++- .../service/zk/AbstractZKClient.java | 2 +- 14 files changed, 234 insertions(+), 88 deletions(-) diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitor.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitor.java index 5cf118800a..391822e535 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitor.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitor.java @@ -50,6 +50,7 @@ public class ResourceTreeVisitor implements Visitor{ * visit * @return resoruce component */ + @Override public ResourceComponent visit() { ResourceComponent rootDirectory = new Directory(); for (Resource resource : resourceList) { @@ -117,6 +118,7 @@ public class ResourceTreeVisitor implements Visitor{ }else{ tempResourceComponent = new FileLeaf(); } + tempResourceComponent.setName(resource.getAlias()); tempResourceComponent.setFullName(resource.getFullName().replaceFirst("/","")); tempResourceComponent.setId(resource.getId()); diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ResourcesService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ResourcesService.java index 8f3075476e..ef1251964c 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ResourcesService.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/ResourcesService.java @@ -104,7 +104,7 @@ public class ResourcesService extends BaseService { putMsg(result, Status.HDFS_NOT_STARTUP); return result; } - String fullName = currentDir.equals("/") ? String.format("%s%s",currentDir,name):String.format("%s/%s",currentDir,name); + String fullName = "/".equals(currentDir) ? String.format("%s%s",currentDir,name):String.format("%s/%s",currentDir,name); if (pid != -1) { Resource parentResource = resourcesMapper.selectById(pid); @@ -229,7 +229,7 @@ public class ResourcesService extends BaseService { } // check resoure name exists - String fullName = currentDir.equals("/") ? String.format("%s%s",currentDir,name):String.format("%s/%s",currentDir,name); + String fullName = "/".equals(currentDir) ? String.format("%s%s",currentDir,name):String.format("%s/%s",currentDir,name); if (checkResourceExists(fullName, 0, type.ordinal())) { logger.error("resource {} has exist, can't recreate", name); putMsg(result, Status.RESOURCE_EXIST); @@ -839,7 +839,7 @@ public class ResourcesService extends BaseService { } String name = fileName.trim() + "." + nameSuffix; - String fullName = currentDirectory.equals("/") ? String.format("%s%s",currentDirectory,name):String.format("%s/%s",currentDirectory,name); + String fullName = "/".equals(currentDirectory) ? String.format("%s%s",currentDirectory,name):String.format("%s/%s",currentDirectory,name); result = verifyResourceName(fullName,type,loginUser); if (!result.getCode().equals(Status.SUCCESS.getCode())) { diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/datax/DataxParameters.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/datax/DataxParameters.java index 872b3aa174..a6f08cd628 100755 --- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/datax/DataxParameters.java +++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/datax/DataxParameters.java @@ -187,7 +187,9 @@ public class DataxParameters extends AbstractParameters { @Override public boolean checkParameters() { - if (customConfig == null) return false; + if (customConfig == null) { + return false; + } if (customConfig == 0) { return dataSource != 0 && dataTarget != 0 diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java index 3505e59fb5..652b981e1e 100644 --- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java +++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/OSUtils.java @@ -57,6 +57,12 @@ public class OSUtils { private OSUtils() {} + /** + * Initialization regularization, solve the problem of pre-compilation performance, + * avoid the thread safety problem of multi-thread operation + */ + private static final Pattern PATTERN = Pattern.compile("\\s+"); + /** * get memory usage @@ -219,8 +225,7 @@ public class OSUtils { List users = new ArrayList<>(); while (startPos <= endPos) { - Pattern pattern = Pattern.compile("\\s+"); - users.addAll(Arrays.asList(pattern.split(lines[startPos]))); + users.addAll(Arrays.asList(PATTERN.split(lines[startPos]))); startPos++; } @@ -313,7 +318,7 @@ public class OSUtils { String currentProcUserName = System.getProperty("user.name"); String result = exeCmd(String.format("net user \"%s\"", currentProcUserName)); String line = result.split("\n")[22]; - String group = Pattern.compile("\\s+").split(line)[1]; + String group = PATTERN.split(line)[1]; if (group.charAt(0) == '*') { return group.substring(1); } else { diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessBuilderForWin32.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessBuilderForWin32.java index eee456d019..9d51eaec1c 100644 --- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessBuilderForWin32.java +++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessBuilderForWin32.java @@ -189,8 +189,9 @@ public class ProcessBuilderForWin32 { * @throws NullPointerException if the argument is null */ public ProcessBuilderForWin32(List command) { - if (command == null) + if (command == null) { throw new NullPointerException(); + } this.command = command; } @@ -207,8 +208,9 @@ public class ProcessBuilderForWin32 { */ public ProcessBuilderForWin32(String... command) { this.command = new ArrayList<>(command.length); - for (String arg : command) + for (String arg : command) { this.command.add(arg); + } } /** @@ -238,8 +240,9 @@ public class ProcessBuilderForWin32 { * @throws NullPointerException if the argument is null */ public ProcessBuilderForWin32 command(List command) { - if (command == null) + if (command == null) { throw new NullPointerException(); + } this.command = command; return this; } @@ -257,8 +260,9 @@ public class ProcessBuilderForWin32 { */ public ProcessBuilderForWin32 command(String... command) { this.command = new ArrayList<>(command.length); - for (String arg : command) + for (String arg : command) { this.command.add(arg); + } return this; } @@ -344,11 +348,13 @@ public class ProcessBuilderForWin32 { */ public Map environment() { SecurityManager security = System.getSecurityManager(); - if (security != null) + if (security != null) { security.checkPermission(new RuntimePermission("getenv.*")); + } - if (environment == null) + if (environment == null) { environment = ProcessEnvironmentForWin32.environment(); + } assert environment != null; @@ -369,15 +375,17 @@ public class ProcessBuilderForWin32 { // for compatibility with old broken code. // Silently discard any trailing junk. - if (envstring.indexOf((int) '\u0000') != -1) + if (envstring.indexOf((int) '\u0000') != -1) { envstring = envstring.replaceFirst("\u0000.*", ""); + } int eqlsign = envstring.indexOf('=', ProcessEnvironmentForWin32.MIN_NAME_LENGTH); // Silently ignore envstrings lacking the required `='. - if (eqlsign != -1) + if (eqlsign != -1) { environment.put(envstring.substring(0,eqlsign), envstring.substring(eqlsign+1)); + } } } return this; @@ -425,6 +433,7 @@ public class ProcessBuilderForWin32 { static class NullInputStream extends InputStream { static final ProcessBuilderForWin32.NullInputStream INSTANCE = new ProcessBuilderForWin32.NullInputStream(); private NullInputStream() {} + @Override public int read() { return -1; } @Override public int available() { return 0; } @@ -436,6 +445,7 @@ public class ProcessBuilderForWin32 { static class NullOutputStream extends OutputStream { static final ProcessBuilderForWin32.NullOutputStream INSTANCE = new ProcessBuilderForWin32.NullOutputStream(); private NullOutputStream() {} + @Override public void write(int b) throws IOException { throw new IOException("Stream closed"); } @@ -516,7 +526,9 @@ public class ProcessBuilderForWin32 { * } */ public static final ProcessBuilderForWin32.Redirect PIPE = new ProcessBuilderForWin32.Redirect() { + @Override public Type type() { return Type.PIPE; } + @Override public String toString() { return type().toString(); }}; /** @@ -531,7 +543,9 @@ public class ProcessBuilderForWin32 { * } */ public static final ProcessBuilderForWin32.Redirect INHERIT = new ProcessBuilderForWin32.Redirect() { + @Override public Type type() { return Type.INHERIT; } + @Override public String toString() { return type().toString(); }}; /** @@ -565,12 +579,15 @@ public class ProcessBuilderForWin32 { * @return a redirect to read from the specified file */ public static ProcessBuilderForWin32.Redirect from(final File file) { - if (file == null) + if (file == null) { throw new NullPointerException(); + } return new ProcessBuilderForWin32.Redirect() { + @Override public Type type() { return Type.READ; } @Override public File file() { return file; } + @Override public String toString() { return "redirect to read from file \"" + file + "\""; } @@ -593,12 +610,15 @@ public class ProcessBuilderForWin32 { * @return a redirect to write to the specified file */ public static ProcessBuilderForWin32.Redirect to(final File file) { - if (file == null) + if (file == null) { throw new NullPointerException(); + } return new ProcessBuilderForWin32.Redirect() { + @Override public Type type() { return Type.WRITE; } @Override public File file() { return file; } + @Override public String toString() { return "redirect to write to file \"" + file + "\""; } @@ -626,12 +646,15 @@ public class ProcessBuilderForWin32 { * @return a redirect to append to the specified file */ public static ProcessBuilderForWin32.Redirect appendTo(final File file) { - if (file == null) + if (file == null) { throw new NullPointerException(); + } return new ProcessBuilderForWin32.Redirect() { + @Override public Type type() { return Type.APPEND; } @Override public File file() { return file; } + @Override public String toString() { return "redirect to append to file \"" + file + "\""; } @@ -647,14 +670,18 @@ public class ProcessBuilderForWin32 { * instances of the same type associated with non-null equal * {@code File} instances. */ + @Override public boolean equals(Object obj) { - if (obj == this) + if (obj == this) { return true; - if (! (obj instanceof ProcessBuilderForWin32.Redirect)) + } + if (! (obj instanceof ProcessBuilderForWin32.Redirect)) { return false; + } ProcessBuilderForWin32.Redirect r = (ProcessBuilderForWin32.Redirect) obj; - if (r.type() != this.type()) + if (r.type() != this.type()) { return false; + } assert this.file() != null; return this.file().equals(r.file()); } @@ -663,12 +690,14 @@ public class ProcessBuilderForWin32 { * Returns a hash code value for this {@code Redirect}. * @return a hash code value for this {@code Redirect} */ + @Override public int hashCode() { File file = file(); - if (file == null) + if (file == null) { return super.hashCode(); - else + } else { return file.hashCode(); + } } /** @@ -679,10 +708,11 @@ public class ProcessBuilderForWin32 { } private ProcessBuilderForWin32.Redirect[] redirects() { - if (redirects == null) - redirects = new ProcessBuilderForWin32.Redirect[] { - ProcessBuilderForWin32.Redirect.PIPE, ProcessBuilderForWin32.Redirect.PIPE, ProcessBuilderForWin32.Redirect.PIPE + if (redirects == null) { + redirects = new Redirect[] { + Redirect.PIPE, Redirect.PIPE, Redirect.PIPE }; + } return redirects; } @@ -711,9 +741,10 @@ public class ProcessBuilderForWin32 { */ public ProcessBuilderForWin32 redirectInput(ProcessBuilderForWin32.Redirect source) { if (source.type() == ProcessBuilderForWin32.Redirect.Type.WRITE || - source.type() == ProcessBuilderForWin32.Redirect.Type.APPEND) + source.type() == ProcessBuilderForWin32.Redirect.Type.APPEND) { throw new IllegalArgumentException( "Redirect invalid for reading: " + source); + } redirects()[0] = source; return this; } @@ -741,9 +772,10 @@ public class ProcessBuilderForWin32 { * @since 1.7 */ public ProcessBuilderForWin32 redirectOutput(ProcessBuilderForWin32.Redirect destination) { - if (destination.type() == ProcessBuilderForWin32.Redirect.Type.READ) + if (destination.type() == ProcessBuilderForWin32.Redirect.Type.READ) { throw new IllegalArgumentException( "Redirect invalid for writing: " + destination); + } redirects()[1] = destination; return this; } @@ -775,9 +807,10 @@ public class ProcessBuilderForWin32 { * @since 1.7 */ public ProcessBuilderForWin32 redirectError(ProcessBuilderForWin32.Redirect destination) { - if (destination.type() == ProcessBuilderForWin32.Redirect.Type.READ) + if (destination.type() == ProcessBuilderForWin32.Redirect.Type.READ) { throw new IllegalArgumentException( "Redirect invalid for writing: " + destination); + } redirects()[2] = destination; return this; } @@ -1019,15 +1052,18 @@ public class ProcessBuilderForWin32 { String[] cmdarray = command.toArray(new String[command.size()]); cmdarray = cmdarray.clone(); - for (String arg : cmdarray) - if (arg == null) + for (String arg : cmdarray) { + if (arg == null) { throw new NullPointerException(); + } + } // Throws IndexOutOfBoundsException if command is empty String prog = cmdarray[0]; SecurityManager security = System.getSecurityManager(); - if (security != null) + if (security != null) { security.checkExec(prog); + } String dir = directory == null ? null : directory.toString(); diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessEnvironmentForWin32.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessEnvironmentForWin32.java index 39fddfbad9..85d9a2120c 100644 --- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessEnvironmentForWin32.java +++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessEnvironmentForWin32.java @@ -27,22 +27,25 @@ final class ProcessEnvironmentForWin32 extends HashMap { private static String validateName(String name) { // An initial `=' indicates a magic Windows variable name -- OK if (name.indexOf('=', 1) != -1 || - name.indexOf('\u0000') != -1) + name.indexOf('\u0000') != -1) { throw new IllegalArgumentException ("Invalid environment variable name: \"" + name + "\""); + } return name; } private static String validateValue(String value) { - if (value.indexOf('\u0000') != -1) + if (value.indexOf('\u0000') != -1) { throw new IllegalArgumentException ("Invalid environment variable value: \"" + value + "\""); + } return value; } private static String nonNullString(Object o) { - if (o == null) + if (o == null) { throw new NullPointerException(); + } return (String) o; } @@ -70,26 +73,38 @@ final class ProcessEnvironmentForWin32 extends HashMap { private static class CheckedEntry implements Entry { private final Entry e; public CheckedEntry(Entry e) {this.e = e;} + @Override public String getKey() { return e.getKey();} + @Override public String getValue() { return e.getValue();} + @Override public String setValue(String value) { return e.setValue(validateValue(value)); } + @Override public String toString() { return getKey() + "=" + getValue();} + @Override public boolean equals(Object o) {return e.equals(o);} + @Override public int hashCode() {return e.hashCode();} } private static class CheckedEntrySet extends AbstractSet> { private final Set> s; public CheckedEntrySet(Set> s) {this.s = s;} + @Override public int size() {return s.size();} + @Override public boolean isEmpty() {return s.isEmpty();} + @Override public void clear() { s.clear();} + @Override public Iterator> iterator() { return new Iterator>() { Iterator> i = s.iterator(); + @Override public boolean hasNext() { return i.hasNext();} + @Override public Entry next() { return new CheckedEntry(i.next()); } @@ -104,18 +119,22 @@ final class ProcessEnvironmentForWin32 extends HashMap { nonNullString(e.getValue()); return e; } + @Override public boolean contains(Object o) {return s.contains(checkedEntry(o));} + @Override public boolean remove(Object o) {return s.remove(checkedEntry(o));} } private static class CheckedValues extends AbstractCollection { private final Collection c; public CheckedValues(Collection c) {this.c = c;} + @Override public int size() {return c.size();} @Override public boolean isEmpty() {return c.isEmpty();} @Override public void clear() { c.clear();} + @Override public Iterator iterator() {return c.iterator();} @Override public boolean contains(Object o) {return c.contains(nonNullString(o));} @@ -126,11 +145,17 @@ final class ProcessEnvironmentForWin32 extends HashMap { private static class CheckedKeySet extends AbstractSet { private final Set s; public CheckedKeySet(Set s) {this.s = s;} + @Override public int size() {return s.size();} + @Override public boolean isEmpty() {return s.isEmpty();} + @Override public void clear() { s.clear();} + @Override public Iterator iterator() {return s.iterator();} + @Override public boolean contains(Object o) {return s.contains(nonNullString(o));} + @Override public boolean remove(Object o) {return s.remove(nonNullString(o));} } @Override @@ -147,6 +172,7 @@ final class ProcessEnvironmentForWin32 extends HashMap { } private static final class NameComparator implements Comparator { + @Override public int compare(String s1, String s2) { // We can't use String.compareToIgnoreCase since it // canonicalizes to lower case, while Windows @@ -163,7 +189,9 @@ final class ProcessEnvironmentForWin32 extends HashMap { c2 = Character.toUpperCase(c2); if (c1 != c2) // No overflow because of numeric promotion + { return c1 - c2; + } } } return n1 - n2; @@ -171,6 +199,7 @@ final class ProcessEnvironmentForWin32 extends HashMap { } private static final class EntryComparator implements Comparator> { + @Override public int compare(Entry e1, Entry e2) { return nameComparator.compare(e1.getKey(), e2.getKey()); @@ -278,8 +307,9 @@ final class ProcessEnvironmentForWin32 extends HashMap { // add the environment variable to the child, if it exists in parent private static void addToEnvIfSet(StringBuilder sb, String name) { String s = getenv(name); - if (s != null) + if (s != null) { addToEnv(sb, name, s); + } } private static void addToEnv(StringBuilder sb, String name, String val) { diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessImplForWin32.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessImplForWin32.java index 4f6d719ef3..1efde52e62 100644 --- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessImplForWin32.java +++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/process/ProcessImplForWin32.java @@ -93,13 +93,15 @@ public class ProcessImplForWin32 extends Process { if (append) { String path = f.getPath(); SecurityManager sm = System.getSecurityManager(); - if (sm != null) + if (sm != null) { sm.checkWrite(path); + } long handle = openForAtomicAppend(path); final FileDescriptor fd = new FileDescriptor(); setHandle(fd, handle); return AccessController.doPrivileged( new PrivilegedAction() { + @Override public FileOutputStream run() { return new FileOutputStream(fd); } @@ -133,30 +135,30 @@ public class ProcessImplForWin32 extends Process { } else { stdHandles = new long[3]; - if (redirects[0] == ProcessBuilderForWin32.Redirect.PIPE) + if (redirects[0] == ProcessBuilderForWin32.Redirect.PIPE) { stdHandles[0] = -1L; - else if (redirects[0] == ProcessBuilderForWin32.Redirect.INHERIT) + } else if (redirects[0] == ProcessBuilderForWin32.Redirect.INHERIT) { stdHandles[0] = getHandle(FileDescriptor.in); - else { + } else { f0 = new FileInputStream(redirects[0].file()); stdHandles[0] = getHandle(f0.getFD()); } - if (redirects[1] == ProcessBuilderForWin32.Redirect.PIPE) + if (redirects[1] == ProcessBuilderForWin32.Redirect.PIPE) { stdHandles[1] = -1L; - else if (redirects[1] == ProcessBuilderForWin32.Redirect.INHERIT) + } else if (redirects[1] == ProcessBuilderForWin32.Redirect.INHERIT) { stdHandles[1] = getHandle(FileDescriptor.out); - else { + } else { f1 = newFileOutputStream(redirects[1].file(), redirects[1].append()); stdHandles[1] = getHandle(f1.getFD()); } - if (redirects[2] == ProcessBuilderForWin32.Redirect.PIPE) + if (redirects[2] == ProcessBuilderForWin32.Redirect.PIPE) { stdHandles[2] = -1L; - else if (redirects[2] == ProcessBuilderForWin32.Redirect.INHERIT) + } else if (redirects[2] == ProcessBuilderForWin32.Redirect.INHERIT) { stdHandles[2] = getHandle(FileDescriptor.err); - else { + } else { f2 = newFileOutputStream(redirects[2].file(), redirects[2].append()); stdHandles[2] = getHandle(f2.getFD()); @@ -167,10 +169,19 @@ public class ProcessImplForWin32 extends Process { } finally { // In theory, close() can throw IOException // (although it is rather unlikely to happen here) - try { if (f0 != null) f0.close(); } + try { if (f0 != null) { + f0.close(); + } + } finally { - try { if (f1 != null) f1.close(); } - finally { if (f2 != null) f2.close(); } + try { if (f1 != null) { + f1.close(); + } + } + finally { if (f2 != null) { + f2.close(); + } + } } } @@ -193,8 +204,9 @@ public class ProcessImplForWin32 extends Process { private static String[] getTokensFromCommand(String command) { ArrayList matchList = new ArrayList<>(8); Matcher regexMatcher = ProcessImplForWin32.LazyPattern.PATTERN.matcher(command); - while (regexMatcher.find()) + while (regexMatcher.find()) { matchList.add(regexMatcher.group()); + } return matchList.toArray(new String[matchList.size()]); } @@ -378,8 +390,9 @@ public class ProcessImplForWin32 extends Process { // .bat files don't include backslashes as part of the quote private static int countLeadingBackslash(int verificationType, CharSequence input, int start) { - if (verificationType == VERIFICATION_CMD_BAT) + if (verificationType == VERIFICATION_CMD_BAT) { return 0; + } int j; for (j = start - 1; j >= 0 && input.charAt(j) == BACKSLASH; j--) { // just scanning backwards @@ -417,8 +430,9 @@ public class ProcessImplForWin32 extends Process { String executablePath = new File(cmd[0]).getPath(); // No worry about internal, unpaired ["], and redirection/piping. - if (needsEscaping(VERIFICATION_LEGACY, executablePath) ) + if (needsEscaping(VERIFICATION_LEGACY, executablePath) ) { executablePath = quoteString(executablePath); + } cmdstr = createCommandLine( //legacy mode doesn't worry about extended verification @@ -442,16 +456,18 @@ public class ProcessImplForWin32 extends Process { // Restore original command line. StringBuilder join = new StringBuilder(); // terminal space in command line is ok - for (String s : cmd) + for (String s : cmd) { join.append(s).append(' '); + } // Parse the command line again. cmd = getTokensFromCommand(join.toString()); executablePath = getExecutablePath(cmd[0]); // Check new executable name once more - if (security != null) + if (security != null) { security.checkExec(executablePath); + } } // Quotation protects from interpretation of the [path] argument as @@ -471,28 +487,29 @@ public class ProcessImplForWin32 extends Process { AccessController.doPrivileged( new PrivilegedAction() { + @Override public Void run() { - if (stdHandles[0] == -1L) + if (stdHandles[0] == -1L) { stdinStream = ProcessBuilderForWin32.NullOutputStream.INSTANCE; - else { + } else { FileDescriptor stdinFd = new FileDescriptor(); setHandle(stdinFd, stdHandles[0]); stdinStream = new BufferedOutputStream( new FileOutputStream(stdinFd)); } - if (stdHandles[1] == -1L) + if (stdHandles[1] == -1L) { stdoutStream = ProcessBuilderForWin32.NullInputStream.INSTANCE; - else { + } else { FileDescriptor stdoutFd = new FileDescriptor(); setHandle(stdoutFd, stdHandles[1]); stdoutStream = new BufferedInputStream( new FileInputStream(stdoutFd)); } - if (stdHandles[2] == -1L) + if (stdHandles[2] == -1L) { stderrStream = ProcessBuilderForWin32.NullInputStream.INSTANCE; - else { + } else { FileDescriptor stderrFd = new FileDescriptor(); setHandle(stderrFd, stdHandles[2]); stderrStream = new FileInputStream(stderrFd); @@ -501,33 +518,41 @@ public class ProcessImplForWin32 extends Process { return null; }}); } + @Override public OutputStream getOutputStream() { return stdinStream; } + @Override public InputStream getInputStream() { return stdoutStream; } + @Override public InputStream getErrorStream() { return stderrStream; } + @Override protected void finalize() { closeHandle(handle); } + @Override public int exitValue() { int exitCode = getExitCodeProcess(handle); - if (exitCode == STILL_ACTIVE) + if (exitCode == STILL_ACTIVE) { throw new IllegalThreadStateException("process has not exited"); + } return exitCode; } + @Override public int waitFor() throws InterruptedException { waitForInterruptibly(handle); - if (Thread.interrupted()) + if (Thread.interrupted()) { throw new InterruptedException(); + } return exitValue(); } @@ -535,8 +560,12 @@ public class ProcessImplForWin32 extends Process { public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { - if (getExitCodeProcess(handle) != STILL_ACTIVE) return true; - if (timeout <= 0) return false; + if (getExitCodeProcess(handle) != STILL_ACTIVE) { + return true; + } + if (timeout <= 0) { + return false; + } long remainingNanos = unit.toNanos(timeout); long deadline = System.nanoTime() + remainingNanos ; @@ -545,8 +574,9 @@ public class ProcessImplForWin32 extends Process { // Round up to next millisecond long msTimeout = TimeUnit.NANOSECONDS.toMillis(remainingNanos + 999_999L); waitForTimeoutInterruptibly(handle, msTimeout); - if (Thread.interrupted()) + if (Thread.interrupted()) { throw new InterruptedException(); + } if (getExitCodeProcess(handle) != STILL_ACTIVE) { return true; } @@ -556,6 +586,7 @@ public class ProcessImplForWin32 extends Process { return (getExitCodeProcess(handle) != STILL_ACTIVE); } + @Override public void destroy() { terminateProcess(handle); } @Override diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/ProcessInstanceMap.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/ProcessInstanceMap.java index 637d573b11..58e5411563 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/ProcessInstanceMap.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/ProcessInstanceMap.java @@ -91,14 +91,24 @@ public class ProcessInstanceMap { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } ProcessInstanceMap that = (ProcessInstanceMap) o; - if (id != that.id) return false; - if (parentProcessInstanceId != that.parentProcessInstanceId) return false; - if (parentTaskInstanceId != that.parentTaskInstanceId) return false; + if (id != that.id) { + return false; + } + if (parentProcessInstanceId != that.parentProcessInstanceId) { + return false; + } + if (parentTaskInstanceId != that.parentTaskInstanceId) { + return false; + } return processInstanceId == that.processInstanceId; } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Queue.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Queue.java index 5d8f7e2149..57b678d2a7 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Queue.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Queue.java @@ -104,13 +104,21 @@ public class Queue { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Queue queue1 = (Queue) o; - if (id != queue1.id) return false; - if (!queueName.equals(queue1.queueName)) return false; + if (id != queue1.id) { + return false; + } + if (!queueName.equals(queue1.queueName)) { + return false; + } return queue.equals(queue1.queue); } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Session.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Session.java index 83bf2461c1..39bf6143dd 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Session.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Session.java @@ -93,14 +93,24 @@ public class Session { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Session session = (Session) o; - if (userId != session.userId) return false; - if (!id.equals(session.id)) return false; - if (!lastLoginTime.equals(session.lastLoginTime)) return false; + if (userId != session.userId) { + return false; + } + if (!id.equals(session.id)) { + return false; + } + if (!lastLoginTime.equals(session.lastLoginTime)) { + return false; + } return ip.equals(session.ip); } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Tenant.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Tenant.java index bf23ad58cf..a289f4f1f5 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Tenant.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/Tenant.java @@ -166,8 +166,12 @@ public class Tenant { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Tenant tenant = (Tenant) o; diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/MysqlPerformance.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/MysqlPerformance.java index 1e1ee78036..e7e9c70f47 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/MysqlPerformance.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/utils/MysqlPerformance.java @@ -56,7 +56,7 @@ public class MysqlPerformance extends BaseDBPerformance{ try (ResultSet rs1 = pstmt.executeQuery("show global variables")) { while(rs1.next()){ - if(rs1.getString(VARIABLE_NAME).equalsIgnoreCase("MAX_CONNECTIONS")){ + if("MAX_CONNECTIONS".equalsIgnoreCase(rs1.getString(VARIABLE_NAME))){ monitorRecord.setMaxConnections( Long.parseLong(rs1.getString("value"))); } } @@ -64,11 +64,11 @@ public class MysqlPerformance extends BaseDBPerformance{ try (ResultSet rs2 = pstmt.executeQuery("show global status")) { while(rs2.next()){ - if(rs2.getString(VARIABLE_NAME).equalsIgnoreCase("MAX_USED_CONNECTIONS")){ + if("MAX_USED_CONNECTIONS".equalsIgnoreCase(rs2.getString(VARIABLE_NAME))){ monitorRecord.setMaxUsedConnections(Long.parseLong(rs2.getString("value"))); - }else if(rs2.getString(VARIABLE_NAME).equalsIgnoreCase("THREADS_CONNECTED")){ + }else if("THREADS_CONNECTED".equalsIgnoreCase(rs2.getString(VARIABLE_NAME))){ monitorRecord.setThreadsConnections(Long.parseLong(rs2.getString("value"))); - }else if(rs2.getString(VARIABLE_NAME).equalsIgnoreCase("THREADS_RUNNING")){ + }else if("THREADS_RUNNING".equalsIgnoreCase(rs2.getString(VARIABLE_NAME))){ monitorRecord.setThreadsRunningConnections(Long.parseLong(rs2.getString("value"))); } } diff --git a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/utils/ProcessUtils.java b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/utils/ProcessUtils.java index 5074a5e0f5..310ab62bf1 100644 --- a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/utils/ProcessUtils.java +++ b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/utils/ProcessUtils.java @@ -46,6 +46,14 @@ public class ProcessUtils { */ private final static Logger logger = LoggerFactory.getLogger(ProcessUtils.class); + /** + * Initialization regularization, solve the problem of pre-compilation performance, + * avoid the thread safety problem of multi-thread operation + */ + private static final Pattern MACPATTERN = Pattern.compile("-[+|-]-\\s(\\d+)"); + + private static final Pattern WINDOWSATTERN = Pattern.compile("(\\d+)"); + /** * build command line characters * @param commandList command list @@ -356,10 +364,10 @@ public class ProcessUtils { // pstree pid get sub pids if (OSUtils.isMacOS()) { String pids = OSUtils.exeCmd("pstree -sp " + processId); - mat = Pattern.compile("-[+|-]-\\s(\\d+)").matcher(pids); + mat = MACPATTERN.matcher(pids); } else { String pids = OSUtils.exeCmd("pstree -p " + processId); - mat = Pattern.compile("(\\d+)").matcher(pids); + mat = WINDOWSATTERN.matcher(pids); } while (mat.find()){ diff --git a/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/AbstractZKClient.java b/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/AbstractZKClient.java index e75e20becb..a27a89af45 100644 --- a/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/AbstractZKClient.java +++ b/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/AbstractZKClient.java @@ -272,7 +272,7 @@ public abstract class AbstractZKClient extends ZookeeperCachedOperator { try { mutex.release(); } catch (Exception e) { - if(e.getMessage().equals("instance must be started before calling this method")){ + if("instance must be started before calling this method".equals(e.getMessage())){ logger.warn("lock release"); }else{ logger.error("lock release failed",e); From 68e3487e348737bdeed71bdeea53eff6e3aaf8c9 Mon Sep 17 00:00:00 2001 From: Rubik-W <39549317+Rubik-W@users.noreply.github.com> Date: Mon, 11 May 2020 11:45:29 +0800 Subject: [PATCH 04/10] feature: Add user state #1923 (#2424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feature: #1923 * fix:docker sql script add column * fix: update sql script * fix: UT bug * fix: UT bug * fix: UT bug * fix: e2e UT bug * fix: e2e button location Co-authored-by: dailidong --- .../docker-entrypoint-initdb/init.sql | 3 ++- .../api/controller/UsersController.java | 25 +++++++++++-------- .../dolphinscheduler/api/enums/Status.java | 1 + .../interceptor/LoginHandlerInterceptor.java | 10 ++++++++ .../api/security/PasswordAuthenticator.java | 8 ++++++ .../api/service/UsersService.java | 14 ++++++++--- .../api/controller/LoginControllerTest.java | 1 - .../LoginHandlerInterceptorTest.java | 6 +++++ .../security/PasswordAuthenticatorTest.java | 8 ++++++ .../api/service/UsersServiceTest.java | 18 +++++++------ .../dolphinscheduler/dao/entity/User.java | 14 +++++++++++ .../dao/mapper/UserMapper.xml | 2 +- .../pages/users/_source/createUser.vue | 15 ++++++++++- .../security/pages/users/_source/list.vue | 12 ++++++--- .../src/js/module/i18n/locale/en_US.js | 4 ++- .../src/js/module/i18n/locale/zh_CN.js | 4 ++- .../locator/security/UserManageLocator.java | 2 +- .../mysql/dolphinscheduler_ddl.sql | 21 ++++++++++++++++ .../postgresql/dolphinscheduler_ddl.sql | 20 +++++++++++++++ 19 files changed, 155 insertions(+), 33 deletions(-) diff --git a/docker/postgres/docker-entrypoint-initdb/init.sql b/docker/postgres/docker-entrypoint-initdb/init.sql index b26520e29c..0251504e27 100755 --- a/docker/postgres/docker-entrypoint-initdb/init.sql +++ b/docker/postgres/docker-entrypoint-initdb/init.sql @@ -623,6 +623,7 @@ CREATE TABLE t_ds_user ( create_time timestamp DEFAULT NULL , update_time timestamp DEFAULT NULL , queue varchar(64) DEFAULT NULL , + state int DEFAULT 1 , PRIMARY KEY (id) ); @@ -749,7 +750,7 @@ ALTER TABLE t_ds_worker_server ALTER COLUMN id SET DEFAULT NEXTVAL('t_ds_worker_ -- Records of t_ds_user?user : admin , password : dolphinscheduler123 -INSERT INTO t_ds_user(user_name,user_password,user_type,email,phone,tenant_id,create_time,update_time) VALUES ('admin', '7ad2410b2f4c074479a8937a28a22b8f', '0', 'xxx@qq.com', 'xx', '0', '2018-03-27 15:48:50', '2018-10-24 17:40:22'); +INSERT INTO t_ds_user(user_name,user_password,user_type,email,phone,state,tenant_id,create_time,update_time) VALUES ('admin', '7ad2410b2f4c074479a8937a28a22b8f', '0', 'xxx@qq.com', 'xx', 1, '0', '2018-03-27 15:48:50', '2018-10-24 17:40:22'); -- Records of t_ds_alertgroup,dolphinscheduler warning group INSERT INTO t_ds_alertgroup(group_name,group_type,description,create_time,update_time) VALUES ('dolphinscheduler warning group', '0', 'dolphinscheduler warning group','2018-11-29 10:20:39', '2018-11-29 10:20:39'); diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java index 08d862e032..456d8c29c7 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java @@ -72,7 +72,8 @@ public class UsersController extends BaseController { @ApiImplicitParam(name = "tenantId", value = "TENANT_ID", dataType = "Int", example = "100"), @ApiImplicitParam(name = "queue", value = "QUEUE", dataType = "Int", example = "100"), @ApiImplicitParam(name = "email", value = "EMAIL", dataType = "Int", example = "100"), - @ApiImplicitParam(name = "phone", value = "PHONE", dataType = "Int", example = "100") + @ApiImplicitParam(name = "phone", value = "PHONE", dataType = "Int", example = "100"), + @ApiImplicitParam(name = "state", value = "STATE", dataType = "Int", example = "1") }) @PostMapping(value = "/create") @ResponseStatus(HttpStatus.CREATED) @@ -83,11 +84,11 @@ public class UsersController extends BaseController { @RequestParam(value = "tenantId") int tenantId, @RequestParam(value = "queue", required = false, defaultValue = "") String queue, @RequestParam(value = "email") String email, - @RequestParam(value = "phone", required = false) String phone) throws Exception { - logger.info("login user {}, create user, userName: {}, email: {}, tenantId: {}, userPassword: {}, phone: {}, user queue: {}", - loginUser.getUserName(), userName, email, tenantId, Constants.PASSWORD_DEFAULT, phone, queue); - - Map result = usersService.createUser(loginUser, userName, userPassword, email, tenantId, phone, queue); + @RequestParam(value = "phone", required = false) String phone, + @RequestParam(value = "state", required = false) int state) throws Exception { + logger.info("login user {}, create user, userName: {}, email: {}, tenantId: {}, userPassword: {}, phone: {}, user queue: {}, state: {}", + loginUser.getUserName(), userName, email, tenantId, Constants.PASSWORD_DEFAULT, phone, queue, state); + Map result = usersService.createUser(loginUser, userName, userPassword, email, tenantId, phone, queue, state); return returnDataList(result); } @@ -146,7 +147,8 @@ public class UsersController extends BaseController { @ApiImplicitParam(name = "tenantId", value = "TENANT_ID", dataType = "Int", example = "100"), @ApiImplicitParam(name = "queue", value = "QUEUE", dataType = "Int", example = "100"), @ApiImplicitParam(name = "email", value = "EMAIL", dataType = "Int", example = "100"), - @ApiImplicitParam(name = "phone", value = "PHONE", dataType = "Int", example = "100") + @ApiImplicitParam(name = "phone", value = "PHONE", dataType = "Int", example = "100"), + @ApiImplicitParam(name = "state", value = "STATE", dataType = "Int", example = "1") }) @PostMapping(value = "/update") @ResponseStatus(HttpStatus.OK) @@ -158,10 +160,11 @@ public class UsersController extends BaseController { @RequestParam(value = "queue", required = false, defaultValue = "") String queue, @RequestParam(value = "email") String email, @RequestParam(value = "tenantId") int tenantId, - @RequestParam(value = "phone", required = false) String phone) throws Exception { - logger.info("login user {}, updateProcessInstance user, userName: {}, email: {}, tenantId: {}, userPassword: {}, phone: {}, user queue: {}", - loginUser.getUserName(), userName, email, tenantId, Constants.PASSWORD_DEFAULT, phone, queue); - Map result = usersService.updateUser(id, userName, userPassword, email, tenantId, phone, queue); + @RequestParam(value = "phone", required = false) String phone, + @RequestParam(value = "state", required = false) int state) throws Exception { + logger.info("login user {}, updateProcessInstance user, userName: {}, email: {}, tenantId: {}, userPassword: {}, phone: {}, user queue: {}, state: {}", + loginUser.getUserName(), userName, email, tenantId, Constants.PASSWORD_DEFAULT, phone, queue, state); + Map result = usersService.updateUser(id, userName, userPassword, email, tenantId, phone, queue, state); return returnDataList(result); } diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java index b3d10da288..ae7300f54d 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/enums/Status.java @@ -175,6 +175,7 @@ public enum Status { QUERY_WORKER_GROUP_FAIL(10146,"query worker group fail ", "查询worker分组失败"), DELETE_WORKER_GROUP_FAIL(10147,"delete worker group fail ", "删除worker分组失败"), COPY_PROCESS_DEFINITION_ERROR(10148,"copy process definition error", "复制工作流错误"), + USER_DISABLED(10149,"The current user is disabled", "当前用户已停用"), UDF_FUNCTION_NOT_EXIST(20001, "UDF function not found", "UDF函数不存在"), UDF_FUNCTION_EXISTS(20002, "UDF function already exists", "UDF函数已存在"), diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptor.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptor.java index 98bac42f72..af29cb67fb 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptor.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptor.java @@ -16,9 +16,11 @@ */ package org.apache.dolphinscheduler.api.interceptor; +import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.security.Authenticator; import org.apache.dolphinscheduler.api.service.SessionService; import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.Flag; import org.apache.dolphinscheduler.dao.entity.User; import org.apache.dolphinscheduler.dao.mapper.UserMapper; import org.apache.commons.httpclient.HttpStatus; @@ -85,6 +87,14 @@ public class LoginHandlerInterceptor implements HandlerInterceptor { return false; } } + + // check user state + if (user.getState() == Flag.NO.ordinal()) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + logger.info(Status.USER_DISABLED.getMsg()); + return false; + } + request.setAttribute(Constants.SESSION_USER, user); return true; } diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticator.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticator.java index a9e287b8e2..69930fc9d7 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticator.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticator.java @@ -21,6 +21,7 @@ import org.apache.dolphinscheduler.api.service.SessionService; import org.apache.dolphinscheduler.api.service.UsersService; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.Flag; import org.apache.dolphinscheduler.dao.entity.Session; import org.apache.dolphinscheduler.dao.entity.User; import org.slf4j.Logger; @@ -49,6 +50,13 @@ public class PasswordAuthenticator implements Authenticator { return result; } + // check user state + if (user.getState() == Flag.NO.ordinal()) { + result.setCode(Status.USER_DISABLED.getCode()); + result.setMsg(Status.USER_DISABLED.getMsg()); + return result; + } + // create session String sessionId = sessionService.createSession(user, extra); if (sessionId == null) { diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java index 220b4fc4d0..bb31733dc7 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java @@ -94,7 +94,8 @@ public class UsersService extends BaseService { String email, int tenantId, String phone, - String queue) throws Exception { + String queue, + int state) throws Exception { Map result = new HashMap<>(5); @@ -115,7 +116,7 @@ public class UsersService extends BaseService { return result; } - User user = createUser(userName, userPassword, email, tenantId, phone, queue); + User user = createUser(userName, userPassword, email, tenantId, phone, queue, state); Tenant tenant = tenantMapper.queryById(tenantId); // resource upload startup @@ -139,7 +140,8 @@ public class UsersService extends BaseService { String email, int tenantId, String phone, - String queue) throws Exception { + String queue, + int state) throws Exception { User user = new User(); Date now = new Date(); @@ -148,6 +150,7 @@ public class UsersService extends BaseService { user.setEmail(email); user.setTenantId(tenantId); user.setPhone(phone); + user.setState(state); // create general users, administrator users are currently built-in user.setUserType(UserType.GENERAL_USER); user.setCreateTime(now); @@ -260,7 +263,8 @@ public class UsersService extends BaseService { String email, int tenantId, String phone, - String queue) throws Exception { + String queue, + int state) throws Exception { Map result = new HashMap<>(5); result.put(Constants.STATUS, false); @@ -309,7 +313,9 @@ public class UsersService extends BaseService { } user.setPhone(phone); } + user.setQueue(queue); + user.setState(state); Date now = new Date(); user.setUpdateTime(now); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java index 5be7b0711c..a4ecd291f9 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java @@ -56,7 +56,6 @@ public class LoginControllerTest extends AbstractControllerTest{ logger.info(mvcResult.getResponse().getContentAsString()); } - @Test public void testSignOut() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java index b8a002ad16..d25a3efa01 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java @@ -57,6 +57,7 @@ public class LoginHandlerInterceptorTest { User mockUser = new User(); mockUser.setId(1); mockUser.setUserType(UserType.GENERAL_USER); + mockUser.setState(1); // test no token when(authenticator.getAuthUser(request)).thenReturn(mockUser); @@ -67,5 +68,10 @@ public class LoginHandlerInterceptorTest { when(request.getHeader("token")).thenReturn(token); when(userMapper.queryUserByToken(token)).thenReturn(mockUser); Assert.assertTrue(interceptor.preHandle(request, response, null)); + + // test disable user + mockUser.setState(0); + when(authenticator.getAuthUser(request)).thenReturn(mockUser); + Assert.assertFalse(interceptor.preHandle(request, response, null)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticatorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticatorTest.java index cccc3079e6..dca70f8ed3 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticatorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/PasswordAuthenticatorTest.java @@ -67,6 +67,7 @@ public class PasswordAuthenticatorTest { mockUser.setEmail("test@test.com"); mockUser.setUserPassword("test"); mockUser.setId(1); + mockUser.setState(1); mockSession = new Session(); mockSession.setId(UUID.randomUUID().toString()); @@ -82,6 +83,13 @@ public class PasswordAuthenticatorTest { Result result = authenticator.authenticate("test", "test", "127.0.0.1"); Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); logger.info(result.toString()); + + mockUser.setState(0); + when(usersService.queryUser("test", "test")).thenReturn(mockUser); + when(sessionService.createSession(mockUser, "127.0.0.1")).thenReturn(mockSession.getId()); + Result result1 = authenticator.authenticate("test", "test", "127.0.0.1"); + Assert.assertEquals(Status.USER_DISABLED.getCode(), (int) result1.getCode()); + logger.info(result1.toString()); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java index 58ee6fdf6c..4c857cbcb1 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java @@ -98,41 +98,42 @@ public class UsersServiceTest { String email = "123@qq.com"; int tenantId = Integer.MAX_VALUE; String phone= "13456432345"; + int state = 1; try { //userName error - Map result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + Map result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userName = "userTest0001"; userPassword = "userTest000111111111111111"; //password error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userPassword = "userTest0001"; email = "1q.com"; //email error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); email = "122222@qq.com"; phone ="2233"; //phone error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); phone = "13456432345"; //tenantId not exists - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.TENANT_NOT_EXIST, result.get(Constants.STATUS)); //success Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - result = usersService.createUser(user, userName, userPassword, email, 1, phone, queueName); + result = usersService.createUser(user, userName, userPassword, email, 1, phone, queueName, state); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); @@ -225,13 +226,13 @@ public class UsersServiceTest { String userPassword = "userTest0001"; try { //user not exist - Map result = usersService.updateUser(0,userName,userPassword,"3443@qq.com",1,"13457864543","queue"); + Map result = usersService.updateUser(0,userName,userPassword,"3443@qq.com",1,"13457864543","queue", 1); Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); logger.info(result.toString()); //success when(userMapper.selectById(1)).thenReturn(getUser()); - result = usersService.updateUser(1,userName,userPassword,"32222s@qq.com",1,"13457864543","queue"); + result = usersService.updateUser(1,userName,userPassword,"32222s@qq.com",1,"13457864543","queue", 1); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { @@ -482,6 +483,7 @@ public class UsersServiceTest { user.setUserType(UserType.ADMIN_USER); user.setUserName("userTest0001"); user.setUserPassword("userTest0001"); + user.setState(1); return user; } diff --git a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/User.java b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/User.java index 8849be0b83..b4f2f93dcc 100644 --- a/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/User.java +++ b/dolphinscheduler-dao/src/main/java/org/apache/dolphinscheduler/dao/entity/User.java @@ -67,6 +67,11 @@ public class User { */ private int tenantId; + /** + * user state + */ + private int state; + /** * tenant code */ @@ -219,6 +224,14 @@ public class User { this.queue = queue; } + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -254,6 +267,7 @@ public class User { ", phone='" + phone + '\'' + ", userType=" + userType + ", tenantId=" + tenantId + + ", state=" + state + ", tenantCode='" + tenantCode + '\'' + ", tenantName='" + tenantName + '\'' + ", queueName='" + queueName + '\'' + diff --git a/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml b/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml index fcf8a137e6..9ad2567237 100644 --- a/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml +++ b/dolphinscheduler-dao/src/main/resources/org/apache/dolphinscheduler/dao/mapper/UserMapper.xml @@ -32,7 +32,7 @@