Skip to content

Commit

Permalink
[Feature][Commons] Linkis Commons Function optimization (#5168)
Browse files Browse the repository at this point in the history
* Custom variable feature enhancement to support more script types for replacement, as well as the YYMMDDHH time-based replacement based on the task submission time.

* LDAP Support cache

* HDFS cache fs do not close

* Support log request info

* Optimize rpc retry

* add new utils method

* Fix build

* Fix build
  • Loading branch information
peacewong authored Sep 10, 2024
1 parent 09f5f22 commit d99f967
Show file tree
Hide file tree
Showing 30 changed files with 609 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

package org.apache.linkis.common.exception;

public class FatalException extends LinkisRuntimeException {
public class FatalException extends LinkisException {
private ExceptionLevel level = ExceptionLevel.FATAL;

public FatalException(int errCode, String desc) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/*
* 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.linkis.common.utils;

import org.apache.linkis.common.exception.ErrorException;
import org.apache.linkis.common.exception.FatalException;
import org.apache.linkis.common.exception.WarnException;

import java.util.concurrent.Callable;
import java.util.function.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LinkisUtils {
private static final Logger logger = LoggerFactory.getLogger(LinkisUtils.class);

public static <T> T tryCatch(Callable<T> tryOp, Function<Throwable, T> catchOp) {
T result = null;
try {
result = tryOp.call();
} catch (Throwable t) {
if (t instanceof FatalException) {
logger.error("Fatal error, system exit...", t);
System.exit(((FatalException) t).getErrCode());
} else if (t instanceof VirtualMachineError) {
logger.error("Fatal error, system exit...", t);
System.exit(-1);
} else if (null != t.getCause()
&& (t.getCause() instanceof FatalException
|| t.getCause() instanceof VirtualMachineError)) {
logger.error("Caused by fatal error, system exit...", t);
System.exit(-1);
} else if (t instanceof Error) {
logger.error("Throw error", t);
throw (Error) t;
} else {
result = catchOp.apply(t);
}
}
return result;
}

public static void tryFinally(Runnable tryOp, Runnable finallyOp) {
try {
tryOp.run();
} finally {
finallyOp.run();
}
}

public static <T> T tryAndWarn(Callable<T> tryOp, Logger log) {
return tryCatch(
tryOp,
t -> {
if (t instanceof ErrorException) {
ErrorException error = (ErrorException) t;
log.error(
"Warning code(警告码): {}, Warning message(警告信息): {}.",
error.getErrCode(),
error.getDesc(),
error);

} else if (t instanceof WarnException) {
WarnException warn = (WarnException) t;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.",
warn.getErrCode(),
warn.getDesc(),
warn);

} else {
log.warn("", t);
}
return null;
});
}

public static void tryAndErrorMsg(Runnable tryOp, String message, Logger log) {
try {
tryOp.run();
} catch (WarnException t) {
WarnException warn = (WarnException) t;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.", warn.getErrCode(), warn.getDesc());
log.warn(message, warn);
} catch (Exception t) {
log.warn(message, t);
}
}

public static <T> void tryAndWarn(Runnable tryOp, Logger log) {
try {
tryOp.run();
} catch (Throwable error) {
if (error instanceof WarnException) {
WarnException warn = (WarnException) error;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.",
warn.getErrCode(),
warn.getDesc(),
error);
} else {
log.warn("", error);
}
}
}

public static void tryAndWarnMsg(Runnable tryOp, String message, Logger log) {
try {
tryOp.run();
} catch (WarnException t) {
WarnException warn = (WarnException) t;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.", warn.getErrCode(), warn.getDesc());
log.warn(message, warn);
} catch (Exception t) {
log.warn(message, t);
}
}

public static <T> T tryAndWarnMsg(Callable<T> tryOp, String message, Logger log) {
return tryCatch(
tryOp,
t -> {
if (t instanceof ErrorException) {
ErrorException error = (ErrorException) t;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.",
error.getErrCode(),
error.getDesc());
log.warn(message, error);
} else if (t instanceof WarnException) {
WarnException warn = (WarnException) t;
log.warn(
"Warning code(警告码): {}, Warning message(警告信息): {}.",
warn.getErrCode(),
warn.getDesc());
log.warn(message, warn);
} else {
log.warn(message, t);
}
return null;
});
}

public static String getJvmUser() {
return System.getProperty("user.name");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* 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.linkis.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

/**
* @param plaintext
* @return
* @throws NoSuchAlgorithmException
*/
public static String encrypt(String plaintext) throws NoSuchAlgorithmException {
// 使用 MD5 算法创建 MessageDigest 对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 更新 MessageDigest 对象中的字节数据
md.update(plaintext.getBytes());
// 对更新后的数据计算哈希值,存储在 byte 数组中
byte[] digest = md.digest();
// 将 byte 数组转换为十六进制字符串
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
// 返回十六进制字符串
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,10 @@

package org.apache.linkis.common.utils;

import org.apache.linkis.common.conf.Configuration;
import org.apache.linkis.common.exception.VariableOperationFailedException;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
Expand Down Expand Up @@ -62,9 +60,16 @@ public class VariableOperationUtils {
* @return
*/
public static ZonedDateTime toZonedDateTime(Date date, ZoneId zoneId) {
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
return ZonedDateTime.of(localDateTime, zoneId);
if (Configuration.VARIABLE_OPERATION_USE_NOW()) {
LocalTime currentTime = LocalTime.now();
LocalDate localDate = date.toInstant().atZone(zoneId).toLocalDate();
LocalDateTime localDateTime = LocalDateTime.of(localDate, currentTime);
return ZonedDateTime.of(localDateTime, zoneId);
} else {
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
return ZonedDateTime.of(localDateTime, zoneId);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ object Configuration extends Logging {

val IS_PROMETHEUS_ENABLE = CommonVars("wds.linkis.prometheus.enable", false)

val IS_MULTIPLE_YARN_CLUSTER = CommonVars("linkis.multiple.yarn.cluster", false)
val IS_MULTIPLE_YARN_CLUSTER = CommonVars("linkis.multiple.yarn.cluster", false).getValue

val PROMETHEUS_ENDPOINT = CommonVars("wds.linkis.prometheus.endpoint", "/actuator/prometheus")

Expand Down Expand Up @@ -70,14 +70,29 @@ object Configuration extends Logging {
// Only the specified token has permission to call some api
val GOVERNANCE_STATION_ADMIN_TOKEN_STARTWITH = "ADMIN-"

val VARIABLE_OPERATION: Boolean = CommonVars("wds.linkis.variable.operation", true).getValue
val VARIABLE_OPERATION_USE_NOW: Boolean =
CommonVars("wds.linkis.variable.operation.use.now", true).getValue

val IS_VIEW_FS_ENV = CommonVars("wds.linkis.env.is.viewfs", true)

val ERROR_MSG_TIP =
CommonVars(
"linkis.jobhistory.error.msg.tip",
"The request interface %s is abnormal. You can try to troubleshoot common problems in the knowledge base document"
)

val LINKIS_TOKEN = CommonVars("wds.linkis.token", "LINKIS-AUTH-eTaYLbQpmIulPyrXcMl")

val GLOBAL_CONF_CHN_NAME = "全局设置"

val GLOBAL_CONF_CHN_OLDNAME = "通用设置"

val GLOBAL_CONF_CHN_EN_NAME = "GlobalSettings"

val GLOBAL_CONF_SYMBOL = "*"

val GLOBAL_CONF_LABEL = "*-*,*-*"

def isAdminToken(token: String): Boolean = {
if (StringUtils.isBlank(token)) {
false
Expand Down Expand Up @@ -137,4 +152,11 @@ object Configuration extends Logging {
(adminUsers ++ historyAdminUsers).distinct
}

def getGlobalCreator(creator: String): String = creator match {
case Configuration.GLOBAL_CONF_CHN_NAME | Configuration.GLOBAL_CONF_CHN_OLDNAME |
Configuration.GLOBAL_CONF_CHN_EN_NAME =>
GLOBAL_CONF_SYMBOL
case _ => creator
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import org.apache.linkis.common.conf.CommonVars

import org.apache.commons.lang3.StringUtils

import java.util.Locale

import scala.collection.mutable

object CodeAndRunTypeUtils {
Expand All @@ -31,7 +33,7 @@ object CodeAndRunTypeUtils {
*/
val CODE_TYPE_AND_RUN_TYPE_RELATION = CommonVars(
"linkis.codeType.language.relation",
"sql=>sql|hql|jdbc|hive|psql|fql|tsql,python=>python|py|pyspark,java=>java,scala=>scala,shell=>sh|shell,json=>json|data_calc"
"sql=>sql|hql|jdbc|hive|psql|fql|tsql|nebula|ngql,python=>python|py|pyspark,java=>java,scala=>scala,shell=>sh|shell,json=>json|data_calc"
)

val LANGUAGE_TYPE_SQL = "sql"
Expand Down Expand Up @@ -117,7 +119,9 @@ object CodeAndRunTypeUtils {
if (StringUtils.isBlank(codeType)) {
return ""
}
getLanguageTypeAndCodeTypeRelationMap.getOrElse(codeType, defaultLanguageType)
val lowerCaseCodeType = codeType.toLowerCase(Locale.getDefault)
getLanguageTypeAndCodeTypeRelationMap.getOrElse(lowerCaseCodeType, defaultLanguageType)

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,17 @@ package org.apache.linkis.common.utils

import org.apache.linkis.common.conf.CommonVars

import org.apache.commons.codec.binary.Hex
import org.apache.commons.lang3.StringUtils

import javax.naming.Context
import javax.naming.ldap.InitialLdapContext

import java.nio.charset.StandardCharsets
import java.util.Hashtable
import java.util.concurrent.TimeUnit

import com.google.common.cache.{Cache, CacheBuilder, RemovalListener, RemovalNotification}

object LDAPUtils extends Logging {

Expand All @@ -38,7 +43,33 @@ object LDAPUtils extends Logging {
val baseDN = CommonVars("wds.linkis.ldap.proxy.baseDN", "").getValue
val userNameFormat = CommonVars("wds.linkis.ldap.proxy.userNameFormat", "").getValue

private val storeUser: Cache[String, String] = CacheBuilder
.newBuilder()
.maximumSize(1000)
.expireAfterWrite(60, TimeUnit.MINUTES)
.removalListener(new RemovalListener[String, String] {

override def onRemoval(removalNotification: RemovalNotification[String, String]): Unit = {
logger.info(s"store user remove key: ${removalNotification.getKey}")
}

})
.build()

def login(userID: String, password: String): Unit = {

val saltPwd = storeUser.getIfPresent(userID)
if (StringUtils.isNotBlank(saltPwd)) {
Utils.tryAndWarn {
if (
saltPwd.equalsIgnoreCase(Hex.encodeHexString(password.getBytes(StandardCharsets.UTF_8)))
) {
logger.info(s"user $userID login success for storeUser")
return
}
}
}

val env = new Hashtable[String, String]()
val bindDN =
if (StringUtils.isBlank(userNameFormat)) userID
Expand All @@ -53,6 +84,9 @@ object LDAPUtils extends Logging {
env.put(Context.SECURITY_CREDENTIALS, bindPassword)

new InitialLdapContext(env, null)
Utils.tryAndWarn {
storeUser.put(userID, Hex.encodeHexString(password.getBytes(StandardCharsets.UTF_8)))
}
logger.info(s"user $userID login success.")

}
Expand Down
Loading

0 comments on commit d99f967

Please sign in to comment.